Don't place html in alt/title attributes, especially with thumbnails
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2 /**
3 * File for Parser and related classes
4 *
5 * @package MediaWiki
6 * @subpackage Parser
7 */
8
9 /** */
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
12
13 /**
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
17 */
18 define( 'MW_PARSER_VERSION', '1.6.0' );
19
20 /**
21 * Variable substitution O(N^2) attack
22 *
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
28 */
29
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
32
33 define( 'RLH_FOR_UPDATE', 1 );
34
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
39
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
45
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
50 # Including space
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
59 );
60
61 /**
62 * PHP Parser
63 *
64 * Processes wiki markup
65 *
66 * <pre>
67 * There are three main entry points into the Parser class:
68 * parse()
69 * produces HTML output
70 * preSaveTransform().
71 * produces altered wiki markup.
72 * transformMsg()
73 * performs brace substitution on MediaWiki messages
74 *
75 * Globals used:
76 * objects: $wgLang, $wgContLang
77 *
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
79 *
80 * settings:
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
84 *
85 * * only within ParserOptions
86 * </pre>
87 *
88 * @package MediaWiki
89 */
90 class Parser
91 {
92 /**#@+
93 * @access private
94 */
95 # Persistent:
96 var $mTagHooks;
97
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
106
107 # Temporary
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
113
114 /**#@-*/
115
116 /**
117 * Constructor
118 *
119 * @access public
120 */
121 function Parser() {
122 $this->mTagHooks = array();
123 $this->clearState();
124 }
125
126 /**
127 * Clear Parser state
128 *
129 * @access private
130 */
131 function clearState() {
132 $this->mOutput = new ParserOutput;
133 $this->mAutonumber = 0;
134 $this->mLastSection = '';
135 $this->mDTopen = false;
136 $this->mVariables = false;
137 $this->mIncludeCount = array();
138 $this->mStripState = array();
139 $this->mArgStack = array();
140 $this->mInPre = false;
141 $this->mInterwikiLinkHolders = array(
142 'texts' => array(),
143 'titles' => array()
144 );
145 $this->mLinkHolders = array(
146 'namespaces' => array(),
147 'dbkeys' => array(),
148 'queries' => array(),
149 'texts' => array(),
150 'titles' => array()
151 );
152 $this->mRevisionId = null;
153 $this->mUniqPrefix = 'UNIQ' . Parser::getRandomString();
154
155 # Clear these on every parse, bug 4549
156 $this->mTemplates = array();
157 $this->mTemplatePath = array();
158
159 wfRunHooks( 'ParserClearState', array( &$this ) );
160 }
161
162 /**
163 * Accessor for mUniqPrefix.
164 *
165 * @access public
166 */
167 function UniqPrefix() {
168 return $this->mUniqPrefix;
169 }
170
171 /**
172 * Convert wikitext to HTML
173 * Do not call this function recursively.
174 *
175 * @access private
176 * @param string $text Text we want to parse
177 * @param Title &$title A title object
178 * @param array $options
179 * @param boolean $linestart
180 * @param boolean $clearState
181 * @param int $revid number to pass in {{REVISIONID}}
182 * @return ParserOutput a ParserOutput
183 */
184 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
185 /**
186 * First pass--just handle <nowiki> sections, pass the rest off
187 * to internalParse() which does all the real work.
188 */
189
190 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
191 $fname = 'Parser::parse';
192 wfProfileIn( $fname );
193
194 if ( $clearState ) {
195 $this->clearState();
196 }
197
198 $this->mOptions = $options;
199 $this->mTitle =& $title;
200 $this->mRevisionId = $revid;
201 $this->mOutputType = OT_HTML;
202
203 $this->mStripState = NULL;
204
205 //$text = $this->strip( $text, $this->mStripState );
206 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
207 $x =& $this->mStripState;
208
209 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
210 $text = $this->strip( $text, $x );
211 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
212
213 # Hook to suspend the parser in this state
214 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
215 wfProfileOut( $fname );
216 return $text ;
217 }
218
219 $text = $this->internalParse( $text );
220
221 $text = $this->unstrip( $text, $this->mStripState );
222
223 # Clean up special characters, only run once, next-to-last before doBlockLevels
224 $fixtags = array(
225 # french spaces, last one Guillemet-left
226 # only if there is something before the space
227 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1&nbsp;\\2',
228 # french spaces, Guillemet-right
229 '/(\\302\\253) /' => '\\1&nbsp;',
230 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
231 );
232 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
233
234 # only once and last
235 $text = $this->doBlockLevels( $text, $linestart );
236
237 $this->replaceLinkHolders( $text );
238
239 # the position of the parserConvert() call should not be changed. it
240 # assumes that the links are all replaced and the only thing left
241 # is the <nowiki> mark.
242 # Side-effects: this calls $this->mOutput->setTitleText()
243 $text = $wgContLang->parserConvert( $text, $this );
244
245 $text = $this->unstripNoWiki( $text, $this->mStripState );
246
247 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
248
249 $text = Sanitizer::normalizeCharReferences( $text );
250
251 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
252 $text = Parser::tidy($text);
253 } else {
254 # attempt to sanitize at least some nesting problems
255 # (bug #2702 and quite a few others)
256 $tidyregs = array(
257 # ''Something [http://www.cool.com cool''] -->
258 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
259 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
260 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
261 # fix up an anchor inside another anchor, only
262 # at least for a single single nested link (bug 3695)
263 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
264 '\\1\\2</a>\\3</a>\\1\\4</a>',
265 # fix div inside inline elements- doBlockLevels won't wrap a line which
266 # contains a div, so fix it up here; replace
267 # div with escaped text
268 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
269 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
270 # remove empty italic or bold tag pairs, some
271 # introduced by rules above
272 '/<([bi])><\/\\1>/' => ''
273 );
274
275 $text = preg_replace(
276 array_keys( $tidyregs ),
277 array_values( $tidyregs ),
278 $text );
279 }
280
281 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
282
283 $this->mOutput->setText( $text );
284 wfProfileOut( $fname );
285
286 return $this->mOutput;
287 }
288
289 /**
290 * Get a random string
291 *
292 * @access private
293 * @static
294 */
295 function getRandomString() {
296 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
297 }
298
299 function &getTitle() { return $this->mTitle; }
300 function getOptions() { return $this->mOptions; }
301
302 /**
303 * Replaces all occurrences of <$tag>content</$tag> in the text
304 * with a random marker and returns the new text. the output parameter
305 * $content will be an associative array filled with data on the form
306 * $unique_marker => content.
307 *
308 * If $content is already set, the additional entries will be appended
309 * If $tag is set to STRIP_COMMENTS, the function will extract
310 * <!-- HTML comments -->
311 *
312 * @access private
313 * @static
314 */
315 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
316 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
317 if ( !$content ) {
318 $content = array( );
319 }
320 $n = 1;
321 $stripped = '';
322
323 if ( !$tags ) {
324 $tags = array( );
325 }
326
327 if ( !$params ) {
328 $params = array( );
329 }
330
331 if( $tag == STRIP_COMMENTS ) {
332 $start = '/<!--()()/';
333 $end = '/-->/';
334 } else {
335 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
336 $end = "/<\\/$tag\\s*>/i";
337 }
338
339 while ( '' != $text ) {
340 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
341 $stripped .= $p[0];
342 if( count( $p ) < 4 ) {
343 break;
344 }
345 $attributes = $p[1];
346 $empty = $p[2];
347 $inside = $p[3];
348
349 $marker = $rnd . sprintf('%08X', $n++);
350 $stripped .= $marker;
351
352 $tags[$marker] = "<$tag$attributes$empty>";
353 $params[$marker] = Sanitizer::decodeTagAttributes( $attributes );
354
355 if ( $empty === '/' ) {
356 // Empty element tag, <tag />
357 $content[$marker] = null;
358 $text = $inside;
359 } else {
360 $q = preg_split( $end, $inside, 2 );
361 $content[$marker] = $q[0];
362 if( count( $q ) < 2 ) {
363 # No end tag -- let it run out to the end of the text.
364 break;
365 } else {
366 $text = $q[1];
367 }
368 }
369 }
370 return $stripped;
371 }
372
373 /**
374 * Wrapper function for extractTagsAndParams
375 * for cases where $tags and $params isn't needed
376 * i.e. where tags will never have params, like <nowiki>
377 *
378 * @access private
379 * @static
380 */
381 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
382 $dummy_tags = array();
383 $dummy_params = array();
384
385 return Parser::extractTagsAndParams( $tag, $text, $content,
386 $dummy_tags, $dummy_params, $uniq_prefix );
387 }
388
389 /**
390 * Strips and renders nowiki, pre, math, hiero
391 * If $render is set, performs necessary rendering operations on plugins
392 * Returns the text, and fills an array with data needed in unstrip()
393 * If the $state is already a valid strip state, it adds to the state
394 *
395 * @param bool $stripcomments when set, HTML comments <!-- like this -->
396 * will be stripped in addition to other tags. This is important
397 * for section editing, where these comments cause confusion when
398 * counting the sections in the wikisource
399 *
400 * @access private
401 */
402 function strip( $text, &$state, $stripcomments = false ) {
403 $render = ($this->mOutputType == OT_HTML);
404 $html_content = array();
405 $nowiki_content = array();
406 $math_content = array();
407 $pre_content = array();
408 $comment_content = array();
409 $ext_content = array();
410 $ext_tags = array();
411 $ext_params = array();
412 $gallery_content = array();
413
414 # Replace any instances of the placeholders
415 $uniq_prefix = $this->mUniqPrefix;
416 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
417
418 # html
419 global $wgRawHtml;
420 if( $wgRawHtml ) {
421 $text = Parser::extractTags('html', $text, $html_content, $uniq_prefix);
422 foreach( $html_content as $marker => $content ) {
423 if ($render ) {
424 # Raw and unchecked for validity.
425 $html_content[$marker] = $content;
426 } else {
427 $html_content[$marker] = '<html>'.$content.'</html>';
428 }
429 }
430 }
431
432 # nowiki
433 $text = Parser::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
434 foreach( $nowiki_content as $marker => $content ) {
435 if( $render ){
436 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
437 } else {
438 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
439 }
440 }
441
442 # math
443 if( $this->mOptions->getUseTeX() ) {
444 $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
445 foreach( $math_content as $marker => $content ){
446 if( $render ) {
447 $math_content[$marker] = renderMath( $content );
448 } else {
449 $math_content[$marker] = '<math>'.$content.'</math>';
450 }
451 }
452 }
453
454 # pre
455 $text = Parser::extractTags('pre', $text, $pre_content, $uniq_prefix);
456 foreach( $pre_content as $marker => $content ){
457 if( $render ){
458 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
459 } else {
460 $pre_content[$marker] = '<pre>'.$content.'</pre>';
461 }
462 }
463
464 # gallery
465 $text = Parser::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
466 foreach( $gallery_content as $marker => $content ) {
467 require_once( 'ImageGallery.php' );
468 if ( $render ) {
469 $gallery_content[$marker] = $this->renderImageGallery( $content );
470 } else {
471 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
472 }
473 }
474
475 # Comments
476 if($stripcomments) {
477 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
478 foreach( $comment_content as $marker => $content ){
479 $comment_content[$marker] = '<!--'.$content.'-->';
480 }
481 }
482
483 # Extensions
484 foreach ( $this->mTagHooks as $tag => $callback ) {
485 $ext_content[$tag] = array();
486 $text = Parser::extractTagsAndParams( $tag, $text, $ext_content[$tag],
487 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
488 foreach( $ext_content[$tag] as $marker => $content ) {
489 $full_tag = $ext_tags[$tag][$marker];
490 $params = $ext_params[$tag][$marker];
491 if ( $render )
492 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
493 else {
494 if ( is_null( $content ) ) {
495 // Empty element tag
496 $ext_content[$tag][$marker] = $full_tag;
497 } else {
498 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
499 }
500 }
501 }
502 }
503
504 # Merge state with the pre-existing state, if there is one
505 if ( $state ) {
506 $state['html'] = $state['html'] + $html_content;
507 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
508 $state['math'] = $state['math'] + $math_content;
509 $state['pre'] = $state['pre'] + $pre_content;
510 $state['gallery'] = $state['gallery'] + $gallery_content;
511 $state['comment'] = $state['comment'] + $comment_content;
512
513 foreach( $ext_content as $tag => $array ) {
514 if ( array_key_exists( $tag, $state ) ) {
515 $state[$tag] = $state[$tag] + $array;
516 }
517 }
518 } else {
519 $state = array(
520 'html' => $html_content,
521 'nowiki' => $nowiki_content,
522 'math' => $math_content,
523 'pre' => $pre_content,
524 'gallery' => $gallery_content,
525 'comment' => $comment_content,
526 ) + $ext_content;
527 }
528 return $text;
529 }
530
531 /**
532 * restores pre, math, and hiero removed by strip()
533 *
534 * always call unstripNoWiki() after this one
535 * @access private
536 */
537 function unstrip( $text, &$state ) {
538 if ( !is_array( $state ) ) {
539 return $text;
540 }
541
542 # Must expand in reverse order, otherwise nested tags will be corrupted
543 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
544 if( $tag != 'nowiki' && $tag != 'html' ) {
545 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
546 $text = str_replace( $uniq, $content, $text );
547 }
548 }
549 }
550
551 return $text;
552 }
553
554 /**
555 * always call this after unstrip() to preserve the order
556 *
557 * @access private
558 */
559 function unstripNoWiki( $text, &$state ) {
560 if ( !is_array( $state ) ) {
561 return $text;
562 }
563
564 # Must expand in reverse order, otherwise nested tags will be corrupted
565 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
566 $text = str_replace( key( $state['nowiki'] ), $content, $text );
567 }
568
569 global $wgRawHtml;
570 if ($wgRawHtml) {
571 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
572 $text = str_replace( key( $state['html'] ), $content, $text );
573 }
574 }
575
576 return $text;
577 }
578
579 /**
580 * Add an item to the strip state
581 * Returns the unique tag which must be inserted into the stripped text
582 * The tag will be replaced with the original text in unstrip()
583 *
584 * @access private
585 */
586 function insertStripItem( $text, &$state ) {
587 $rnd = $this->mUniqPrefix . '-item' . Parser::getRandomString();
588 if ( !$state ) {
589 $state = array(
590 'html' => array(),
591 'nowiki' => array(),
592 'math' => array(),
593 'pre' => array(),
594 'comment' => array(),
595 'gallery' => array(),
596 );
597 }
598 $state['item'][$rnd] = $text;
599 return $rnd;
600 }
601
602 /**
603 * Interface with html tidy, used if $wgUseTidy = true.
604 * If tidy isn't able to correct the markup, the original will be
605 * returned in all its glory with a warning comment appended.
606 *
607 * Either the external tidy program or the in-process tidy extension
608 * will be used depending on availability. Override the default
609 * $wgTidyInternal setting to disable the internal if it's not working.
610 *
611 * @param string $text Hideous HTML input
612 * @return string Corrected HTML output
613 * @access public
614 * @static
615 */
616 function tidy( $text ) {
617 global $wgTidyInternal;
618 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
619 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
620 '<head><title>test</title></head><body>'.$text.'</body></html>';
621 if( $wgTidyInternal ) {
622 $correctedtext = Parser::internalTidy( $wrappedtext );
623 } else {
624 $correctedtext = Parser::externalTidy( $wrappedtext );
625 }
626 if( is_null( $correctedtext ) ) {
627 wfDebug( "Tidy error detected!\n" );
628 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
629 }
630 return $correctedtext;
631 }
632
633 /**
634 * Spawn an external HTML tidy process and get corrected markup back from it.
635 *
636 * @access private
637 * @static
638 */
639 function externalTidy( $text ) {
640 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
641 $fname = 'Parser::externalTidy';
642 wfProfileIn( $fname );
643
644 $cleansource = '';
645 $opts = ' -utf8';
646
647 $descriptorspec = array(
648 0 => array('pipe', 'r'),
649 1 => array('pipe', 'w'),
650 2 => array('file', '/dev/null', 'a')
651 );
652 $pipes = array();
653 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
654 if (is_resource($process)) {
655 // Theoretically, this style of communication could cause a deadlock
656 // here. If the stdout buffer fills up, then writes to stdin could
657 // block. This doesn't appear to happen with tidy, because tidy only
658 // writes to stdout after it's finished reading from stdin. Search
659 // for tidyParseStdin and tidySaveStdout in console/tidy.c
660 fwrite($pipes[0], $text);
661 fclose($pipes[0]);
662 while (!feof($pipes[1])) {
663 $cleansource .= fgets($pipes[1], 1024);
664 }
665 fclose($pipes[1]);
666 proc_close($process);
667 }
668
669 wfProfileOut( $fname );
670
671 if( $cleansource == '' && $text != '') {
672 // Some kind of error happened, so we couldn't get the corrected text.
673 // Just give up; we'll use the source text and append a warning.
674 return null;
675 } else {
676 return $cleansource;
677 }
678 }
679
680 /**
681 * Use the HTML tidy PECL extension to use the tidy library in-process,
682 * saving the overhead of spawning a new process. Currently written to
683 * the PHP 4.3.x version of the extension, may not work on PHP 5.
684 *
685 * 'pear install tidy' should be able to compile the extension module.
686 *
687 * @access private
688 * @static
689 */
690 function internalTidy( $text ) {
691 global $wgTidyConf;
692 $fname = 'Parser::internalTidy';
693 wfProfileIn( $fname );
694
695 tidy_load_config( $wgTidyConf );
696 tidy_set_encoding( 'utf8' );
697 tidy_parse_string( $text );
698 tidy_clean_repair();
699 if( tidy_get_status() == 2 ) {
700 // 2 is magic number for fatal error
701 // http://www.php.net/manual/en/function.tidy-get-status.php
702 $cleansource = null;
703 } else {
704 $cleansource = tidy_get_output();
705 }
706 wfProfileOut( $fname );
707 return $cleansource;
708 }
709
710 /**
711 * parse the wiki syntax used to render tables
712 *
713 * @access private
714 */
715 function doTableStuff ( $t ) {
716 $fname = 'Parser::doTableStuff';
717 wfProfileIn( $fname );
718
719 $t = explode ( "\n" , $t ) ;
720 $td = array () ; # Is currently a td tag open?
721 $ltd = array () ; # Was it TD or TH?
722 $tr = array () ; # Is currently a tr tag open?
723 $ltr = array () ; # tr attributes
724 $has_opened_tr = array(); # Did this table open a <tr> element?
725 $indent_level = 0; # indent level of the table
726 foreach ( $t AS $k => $x )
727 {
728 $x = trim ( $x ) ;
729 $fc = substr ( $x , 0 , 1 ) ;
730 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
731 $indent_level = strlen( $matches[1] );
732
733 $attributes = $this->unstripForHTML( $matches[2] );
734
735 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
736 '<table' . Sanitizer::fixTagAttributes ( $attributes, 'table' ) . '>' ;
737 array_push ( $td , false ) ;
738 array_push ( $ltd , '' ) ;
739 array_push ( $tr , false ) ;
740 array_push ( $ltr , '' ) ;
741 array_push ( $has_opened_tr, false );
742 }
743 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
744 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
745 $z = "</table>" . substr ( $x , 2);
746 $l = array_pop ( $ltd ) ;
747 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
748 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
749 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
750 array_pop ( $ltr ) ;
751 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
752 }
753 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
754 $x = substr ( $x , 1 ) ;
755 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
756 $z = '' ;
757 $l = array_pop ( $ltd ) ;
758 array_pop ( $has_opened_tr );
759 array_push ( $has_opened_tr , true ) ;
760 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
761 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
762 array_pop ( $ltr ) ;
763 $t[$k] = $z ;
764 array_push ( $tr , false ) ;
765 array_push ( $td , false ) ;
766 array_push ( $ltd , '' ) ;
767 $attributes = $this->unstripForHTML( $x );
768 array_push ( $ltr , Sanitizer::fixTagAttributes ( $attributes, 'tr' ) ) ;
769 }
770 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) { # Caption
771 # $x is a table row
772 if ( '|+' == substr ( $x , 0 , 2 ) ) {
773 $fc = '+' ;
774 $x = substr ( $x , 1 ) ;
775 }
776 $after = substr ( $x , 1 ) ;
777 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
778 $after = explode ( '||' , $after ) ;
779 $t[$k] = '' ;
780
781 # Loop through each table cell
782 foreach ( $after AS $theline )
783 {
784 $z = '' ;
785 if ( $fc != '+' )
786 {
787 $tra = array_pop ( $ltr ) ;
788 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
789 array_push ( $tr , true ) ;
790 array_push ( $ltr , '' ) ;
791 array_pop ( $has_opened_tr );
792 array_push ( $has_opened_tr , true ) ;
793 }
794
795 $l = array_pop ( $ltd ) ;
796 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
797 if ( $fc == '|' ) $l = 'td' ;
798 else if ( $fc == '!' ) $l = 'th' ;
799 else if ( $fc == '+' ) $l = 'caption' ;
800 else $l = '' ;
801 array_push ( $ltd , $l ) ;
802
803 # Cell parameters
804 $y = explode ( '|' , $theline , 2 ) ;
805 # Note that a '|' inside an invalid link should not
806 # be mistaken as delimiting cell parameters
807 if ( strpos( $y[0], '[[' ) !== false ) {
808 $y = array ($theline);
809 }
810 if ( count ( $y ) == 1 )
811 $y = "{$z}<{$l}>{$y[0]}" ;
812 else {
813 $attributes = $this->unstripForHTML( $y[0] );
814 $y = "{$z}<{$l}".Sanitizer::fixTagAttributes($attributes, $l).">{$y[1]}" ;
815 }
816 $t[$k] .= $y ;
817 array_push ( $td , true ) ;
818 }
819 }
820 }
821
822 # Closing open td, tr && table
823 while ( count ( $td ) > 0 )
824 {
825 $l = array_pop ( $ltd ) ;
826 if ( array_pop ( $td ) ) $t[] = '</td>' ;
827 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
828 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
829 $t[] = '</table>' ;
830 }
831
832 $t = implode ( "\n" , $t ) ;
833 # special case: don't return empty table
834 if($t == "<table>\n<tr><td></td></tr>\n</table>")
835 $t = '';
836 wfProfileOut( $fname );
837 return $t ;
838 }
839
840 /**
841 * Helper function for parse() that transforms wiki markup into
842 * HTML. Only called for $mOutputType == OT_HTML.
843 *
844 * @access private
845 */
846 function internalParse( $text ) {
847 $args = array();
848 $isMain = true;
849 $fname = 'Parser::internalParse';
850 wfProfileIn( $fname );
851
852 # Remove <noinclude> tags and <includeonly> sections
853 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
854 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
855 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
856
857 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
858 $text = $this->replaceVariables( $text, $args );
859
860 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
861
862 $text = $this->doHeadings( $text );
863 if($this->mOptions->getUseDynamicDates()) {
864 $df =& DateFormatter::getInstance();
865 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
866 }
867 $text = $this->doAllQuotes( $text );
868 $text = $this->replaceInternalLinks( $text );
869 $text = $this->replaceExternalLinks( $text );
870
871 # replaceInternalLinks may sometimes leave behind
872 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
873 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
874
875 $text = $this->doMagicLinks( $text );
876 $text = $this->doTableStuff( $text );
877 $text = $this->formatHeadings( $text, $isMain );
878
879 wfProfileOut( $fname );
880 return $text;
881 }
882
883 /**
884 * Replace special strings like "ISBN xxx" and "RFC xxx" with
885 * magic external links.
886 *
887 * @access private
888 */
889 function &doMagicLinks( &$text ) {
890 $text = $this->magicISBN( $text );
891 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
892 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
893 return $text;
894 }
895
896 /**
897 * Parse headers and return html
898 *
899 * @access private
900 */
901 function doHeadings( $text ) {
902 $fname = 'Parser::doHeadings';
903 wfProfileIn( $fname );
904 for ( $i = 6; $i >= 1; --$i ) {
905 $h = str_repeat( '=', $i );
906 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
907 "<h{$i}>\\1</h{$i}>\\2", $text );
908 }
909 wfProfileOut( $fname );
910 return $text;
911 }
912
913 /**
914 * Replace single quotes with HTML markup
915 * @access private
916 * @return string the altered text
917 */
918 function doAllQuotes( $text ) {
919 $fname = 'Parser::doAllQuotes';
920 wfProfileIn( $fname );
921 $outtext = '';
922 $lines = explode( "\n", $text );
923 foreach ( $lines as $line ) {
924 $outtext .= $this->doQuotes ( $line ) . "\n";
925 }
926 $outtext = substr($outtext, 0,-1);
927 wfProfileOut( $fname );
928 return $outtext;
929 }
930
931 /**
932 * Helper function for doAllQuotes()
933 * @access private
934 */
935 function doQuotes( $text ) {
936 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
937 if ( count( $arr ) == 1 )
938 return $text;
939 else
940 {
941 # First, do some preliminary work. This may shift some apostrophes from
942 # being mark-up to being text. It also counts the number of occurrences
943 # of bold and italics mark-ups.
944 $i = 0;
945 $numbold = 0;
946 $numitalics = 0;
947 foreach ( $arr as $r )
948 {
949 if ( ( $i % 2 ) == 1 )
950 {
951 # If there are ever four apostrophes, assume the first is supposed to
952 # be text, and the remaining three constitute mark-up for bold text.
953 if ( strlen( $arr[$i] ) == 4 )
954 {
955 $arr[$i-1] .= "'";
956 $arr[$i] = "'''";
957 }
958 # If there are more than 5 apostrophes in a row, assume they're all
959 # text except for the last 5.
960 else if ( strlen( $arr[$i] ) > 5 )
961 {
962 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
963 $arr[$i] = "'''''";
964 }
965 # Count the number of occurrences of bold and italics mark-ups.
966 # We are not counting sequences of five apostrophes.
967 if ( strlen( $arr[$i] ) == 2 ) $numitalics++; else
968 if ( strlen( $arr[$i] ) == 3 ) $numbold++; else
969 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
970 }
971 $i++;
972 }
973
974 # If there is an odd number of both bold and italics, it is likely
975 # that one of the bold ones was meant to be an apostrophe followed
976 # by italics. Which one we cannot know for certain, but it is more
977 # likely to be one that has a single-letter word before it.
978 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
979 {
980 $i = 0;
981 $firstsingleletterword = -1;
982 $firstmultiletterword = -1;
983 $firstspace = -1;
984 foreach ( $arr as $r )
985 {
986 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
987 {
988 $x1 = substr ($arr[$i-1], -1);
989 $x2 = substr ($arr[$i-1], -2, 1);
990 if ($x1 == ' ') {
991 if ($firstspace == -1) $firstspace = $i;
992 } else if ($x2 == ' ') {
993 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
994 } else {
995 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
996 }
997 }
998 $i++;
999 }
1000
1001 # If there is a single-letter word, use it!
1002 if ($firstsingleletterword > -1)
1003 {
1004 $arr [ $firstsingleletterword ] = "''";
1005 $arr [ $firstsingleletterword-1 ] .= "'";
1006 }
1007 # If not, but there's a multi-letter word, use that one.
1008 else if ($firstmultiletterword > -1)
1009 {
1010 $arr [ $firstmultiletterword ] = "''";
1011 $arr [ $firstmultiletterword-1 ] .= "'";
1012 }
1013 # ... otherwise use the first one that has neither.
1014 # (notice that it is possible for all three to be -1 if, for example,
1015 # there is only one pentuple-apostrophe in the line)
1016 else if ($firstspace > -1)
1017 {
1018 $arr [ $firstspace ] = "''";
1019 $arr [ $firstspace-1 ] .= "'";
1020 }
1021 }
1022
1023 # Now let's actually convert our apostrophic mush to HTML!
1024 $output = '';
1025 $buffer = '';
1026 $state = '';
1027 $i = 0;
1028 foreach ($arr as $r)
1029 {
1030 if (($i % 2) == 0)
1031 {
1032 if ($state == 'both')
1033 $buffer .= $r;
1034 else
1035 $output .= $r;
1036 }
1037 else
1038 {
1039 if (strlen ($r) == 2)
1040 {
1041 if ($state == 'i')
1042 { $output .= '</i>'; $state = ''; }
1043 else if ($state == 'bi')
1044 { $output .= '</i>'; $state = 'b'; }
1045 else if ($state == 'ib')
1046 { $output .= '</b></i><b>'; $state = 'b'; }
1047 else if ($state == 'both')
1048 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1049 else # $state can be 'b' or ''
1050 { $output .= '<i>'; $state .= 'i'; }
1051 }
1052 else if (strlen ($r) == 3)
1053 {
1054 if ($state == 'b')
1055 { $output .= '</b>'; $state = ''; }
1056 else if ($state == 'bi')
1057 { $output .= '</i></b><i>'; $state = 'i'; }
1058 else if ($state == 'ib')
1059 { $output .= '</b>'; $state = 'i'; }
1060 else if ($state == 'both')
1061 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1062 else # $state can be 'i' or ''
1063 { $output .= '<b>'; $state .= 'b'; }
1064 }
1065 else if (strlen ($r) == 5)
1066 {
1067 if ($state == 'b')
1068 { $output .= '</b><i>'; $state = 'i'; }
1069 else if ($state == 'i')
1070 { $output .= '</i><b>'; $state = 'b'; }
1071 else if ($state == 'bi')
1072 { $output .= '</i></b>'; $state = ''; }
1073 else if ($state == 'ib')
1074 { $output .= '</b></i>'; $state = ''; }
1075 else if ($state == 'both')
1076 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1077 else # ($state == '')
1078 { $buffer = ''; $state = 'both'; }
1079 }
1080 }
1081 $i++;
1082 }
1083 # Now close all remaining tags. Notice that the order is important.
1084 if ($state == 'b' || $state == 'ib')
1085 $output .= '</b>';
1086 if ($state == 'i' || $state == 'bi' || $state == 'ib')
1087 $output .= '</i>';
1088 if ($state == 'bi')
1089 $output .= '</b>';
1090 if ($state == 'both')
1091 $output .= '<b><i>'.$buffer.'</i></b>';
1092 return $output;
1093 }
1094 }
1095
1096 /**
1097 * Replace external links
1098 *
1099 * Note: this is all very hackish and the order of execution matters a lot.
1100 * Make sure to run maintenance/parserTests.php if you change this code.
1101 *
1102 * @access private
1103 */
1104 function replaceExternalLinks( $text ) {
1105 global $wgContLang;
1106 $fname = 'Parser::replaceExternalLinks';
1107 wfProfileIn( $fname );
1108
1109 $sk =& $this->mOptions->getSkin();
1110
1111 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1112
1113 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1114
1115 $i = 0;
1116 while ( $i<count( $bits ) ) {
1117 $url = $bits[$i++];
1118 $protocol = $bits[$i++];
1119 $text = $bits[$i++];
1120 $trail = $bits[$i++];
1121
1122 # The characters '<' and '>' (which were escaped by
1123 # removeHTMLtags()) should not be included in
1124 # URLs, per RFC 2396.
1125 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1126 $text = substr($url, $m2[0][1]) . ' ' . $text;
1127 $url = substr($url, 0, $m2[0][1]);
1128 }
1129
1130 # If the link text is an image URL, replace it with an <img> tag
1131 # This happened by accident in the original parser, but some people used it extensively
1132 $img = $this->maybeMakeExternalImage( $text );
1133 if ( $img !== false ) {
1134 $text = $img;
1135 }
1136
1137 $dtrail = '';
1138
1139 # Set linktype for CSS - if URL==text, link is essentially free
1140 $linktype = ($text == $url) ? 'free' : 'text';
1141
1142 # No link text, e.g. [http://domain.tld/some.link]
1143 if ( $text == '' ) {
1144 # Autonumber if allowed
1145 if ( strpos( HTTP_PROTOCOLS, str_replace('/','\/', $protocol) ) !== false ) {
1146 $text = '[' . ++$this->mAutonumber . ']';
1147 $linktype = 'autonumber';
1148 } else {
1149 # Otherwise just use the URL
1150 $text = htmlspecialchars( $url );
1151 $linktype = 'free';
1152 }
1153 } else {
1154 # Have link text, e.g. [http://domain.tld/some.link text]s
1155 # Check for trail
1156 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1157 }
1158
1159 $text = $wgContLang->markNoConversion($text);
1160
1161 # Replace &amp; from obsolete syntax with &.
1162 # All HTML entities will be escaped by makeExternalLink()
1163 $url = str_replace( '&amp;', '&', $url );
1164
1165 # Process the trail (i.e. everything after this link up until start of the next link),
1166 # replacing any non-bracketed links
1167 $trail = $this->replaceFreeExternalLinks( $trail );
1168
1169 # Use the encoded URL
1170 # This means that users can paste URLs directly into the text
1171 # Funny characters like &ouml; aren't valid in URLs anyway
1172 # This was changed in August 2004
1173 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1174
1175 # Register link in the output object.
1176 # Replace unnecessary URL escape codes with the referenced character
1177 # This prevents spammers from hiding links from the filters
1178 $pasteurized = Parser::replaceUnusualEscapes( $url );
1179 $this->mOutput->addExternalLink( $pasteurized );
1180 }
1181
1182 wfProfileOut( $fname );
1183 return $s;
1184 }
1185
1186 /**
1187 * Replace anything that looks like a URL with a link
1188 * @access private
1189 */
1190 function replaceFreeExternalLinks( $text ) {
1191 global $wgContLang;
1192 $fname = 'Parser::replaceFreeExternalLinks';
1193 wfProfileIn( $fname );
1194
1195 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1196 $s = array_shift( $bits );
1197 $i = 0;
1198
1199 $sk =& $this->mOptions->getSkin();
1200
1201 while ( $i < count( $bits ) ){
1202 $protocol = $bits[$i++];
1203 $remainder = $bits[$i++];
1204
1205 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1206 # Found some characters after the protocol that look promising
1207 $url = $protocol . $m[1];
1208 $trail = $m[2];
1209
1210 # special case: handle urls as url args:
1211 # http://www.example.com/foo?=http://www.example.com/bar
1212 if(strlen($trail) == 0 &&
1213 isset($bits[$i]) &&
1214 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1215 preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $bits[$i + 1], $m ))
1216 {
1217 # add protocol, arg
1218 $url .= $bits[$i] . $bits[$i + 1]; # protocol, url as arg to previous link
1219 $i += 2;
1220 $trail = $m[2];
1221 }
1222
1223 # The characters '<' and '>' (which were escaped by
1224 # removeHTMLtags()) should not be included in
1225 # URLs, per RFC 2396.
1226 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1227 $trail = substr($url, $m2[0][1]) . $trail;
1228 $url = substr($url, 0, $m2[0][1]);
1229 }
1230
1231 # Move trailing punctuation to $trail
1232 $sep = ',;\.:!?';
1233 # If there is no left bracket, then consider right brackets fair game too
1234 if ( strpos( $url, '(' ) === false ) {
1235 $sep .= ')';
1236 }
1237
1238 $numSepChars = strspn( strrev( $url ), $sep );
1239 if ( $numSepChars ) {
1240 $trail = substr( $url, -$numSepChars ) . $trail;
1241 $url = substr( $url, 0, -$numSepChars );
1242 }
1243
1244 # Replace &amp; from obsolete syntax with &.
1245 # All HTML entities will be escaped by makeExternalLink()
1246 # or maybeMakeExternalImage()
1247 $url = str_replace( '&amp;', '&', $url );
1248
1249 # Is this an external image?
1250 $text = $this->maybeMakeExternalImage( $url );
1251 if ( $text === false ) {
1252 # Not an image, make a link
1253 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1254 # Register it in the output object...
1255 # Replace unnecessary URL escape codes with their equivalent characters
1256 $pasteurized = Parser::replaceUnusualEscapes( $url );
1257 $this->mOutput->addExternalLink( $pasteurized );
1258 }
1259 $s .= $text . $trail;
1260 } else {
1261 $s .= $protocol . $remainder;
1262 }
1263 }
1264 wfProfileOut( $fname );
1265 return $s;
1266 }
1267
1268 /**
1269 * Replace unusual URL escape codes with their equivalent characters
1270 * @param string
1271 * @return string
1272 * @static
1273 * @fixme This can merge genuinely required bits in the path or query string,
1274 * breaking legit URLs. A proper fix would treat the various parts of
1275 * the URL differently; as a workaround, just use the output for
1276 * statistical records, not for actual linking/output.
1277 */
1278 function replaceUnusualEscapes( $url ) {
1279 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1280 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1281 }
1282
1283 /**
1284 * Callback function used in replaceUnusualEscapes().
1285 * Replaces unusual URL escape codes with their equivalent character
1286 * @static
1287 * @access private
1288 */
1289 function replaceUnusualEscapesCallback( $matches ) {
1290 $char = urldecode( $matches[0] );
1291 $ord = ord( $char );
1292 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1293 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1294 // No, shouldn't be escaped
1295 return $char;
1296 } else {
1297 // Yes, leave it escaped
1298 return $matches[0];
1299 }
1300 }
1301
1302 /**
1303 * make an image if it's allowed, either through the global
1304 * option or through the exception
1305 * @access private
1306 */
1307 function maybeMakeExternalImage( $url ) {
1308 $sk =& $this->mOptions->getSkin();
1309 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1310 $imagesexception = !empty($imagesfrom);
1311 $text = false;
1312 if ( $this->mOptions->getAllowExternalImages()
1313 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1314 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1315 # Image found
1316 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1317 }
1318 }
1319 return $text;
1320 }
1321
1322 /**
1323 * Process [[ ]] wikilinks
1324 *
1325 * @access private
1326 */
1327 function replaceInternalLinks( $s ) {
1328 global $wgContLang;
1329 static $fname = 'Parser::replaceInternalLinks' ;
1330
1331 wfProfileIn( $fname );
1332
1333 wfProfileIn( $fname.'-setup' );
1334 static $tc = FALSE;
1335 # the % is needed to support urlencoded titles as well
1336 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1337
1338 $sk =& $this->mOptions->getSkin();
1339
1340 #split the entire text string on occurences of [[
1341 $a = explode( '[[', ' ' . $s );
1342 #get the first element (all text up to first [[), and remove the space we added
1343 $s = array_shift( $a );
1344 $s = substr( $s, 1 );
1345
1346 # Match a link having the form [[namespace:link|alternate]]trail
1347 static $e1 = FALSE;
1348 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1349 # Match cases where there is no "]]", which might still be images
1350 static $e1_img = FALSE;
1351 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1352 # Match the end of a line for a word that's not followed by whitespace,
1353 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1354 $e2 = wfMsgForContent( 'linkprefix' );
1355
1356 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1357
1358 if( is_null( $this->mTitle ) ) {
1359 wfDebugDieBacktrace( 'nooo' );
1360 }
1361 $nottalk = !$this->mTitle->isTalkPage();
1362
1363 if ( $useLinkPrefixExtension ) {
1364 if ( preg_match( $e2, $s, $m ) ) {
1365 $first_prefix = $m[2];
1366 } else {
1367 $first_prefix = false;
1368 }
1369 } else {
1370 $prefix = '';
1371 }
1372
1373 $selflink = $this->mTitle->getPrefixedText();
1374 wfProfileOut( $fname.'-setup' );
1375
1376 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1377 $useSubpages = $this->areSubpagesAllowed();
1378
1379 # Loop for each link
1380 for ($k = 0; isset( $a[$k] ); $k++) {
1381 $line = $a[$k];
1382 if ( $useLinkPrefixExtension ) {
1383 wfProfileIn( $fname.'-prefixhandling' );
1384 if ( preg_match( $e2, $s, $m ) ) {
1385 $prefix = $m[2];
1386 $s = $m[1];
1387 } else {
1388 $prefix='';
1389 }
1390 # first link
1391 if($first_prefix) {
1392 $prefix = $first_prefix;
1393 $first_prefix = false;
1394 }
1395 wfProfileOut( $fname.'-prefixhandling' );
1396 }
1397
1398 $might_be_img = false;
1399
1400 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1401 $text = $m[2];
1402 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1403 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1404 # the real problem is with the $e1 regex
1405 # See bug 1300.
1406 #
1407 # Still some problems for cases where the ] is meant to be outside punctuation,
1408 # and no image is in sight. See bug 2095.
1409 #
1410 if( $text !== '' &&
1411 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1412 strpos($text, '[') !== false
1413 )
1414 {
1415 $text .= ']'; # so that replaceExternalLinks($text) works later
1416 $m[3] = $n[1];
1417 }
1418 # fix up urlencoded title texts
1419 if(preg_match('/%/', $m[1] ))
1420 # Should anchors '#' also be rejected?
1421 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1422 $trail = $m[3];
1423 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1424 $might_be_img = true;
1425 $text = $m[2];
1426 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1427 $trail = "";
1428 } else { # Invalid form; output directly
1429 $s .= $prefix . '[[' . $line ;
1430 continue;
1431 }
1432
1433 # Don't allow internal links to pages containing
1434 # PROTO: where PROTO is a valid URL protocol; these
1435 # should be external links.
1436 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1437 $s .= $prefix . '[[' . $line ;
1438 continue;
1439 }
1440
1441 # Make subpage if necessary
1442 if( $useSubpages ) {
1443 $link = $this->maybeDoSubpageLink( $m[1], $text );
1444 } else {
1445 $link = $m[1];
1446 }
1447
1448 $noforce = (substr($m[1], 0, 1) != ':');
1449 if (!$noforce) {
1450 # Strip off leading ':'
1451 $link = substr($link, 1);
1452 }
1453
1454 $nt = Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1455 if( !$nt ) {
1456 $s .= $prefix . '[[' . $line;
1457 continue;
1458 }
1459
1460 #check other language variants of the link
1461 #if the article does not exist
1462 if( $checkVariantLink
1463 && $nt->getArticleID() == 0 ) {
1464 $wgContLang->findVariantLink($link, $nt);
1465 }
1466
1467 $ns = $nt->getNamespace();
1468 $iw = $nt->getInterWiki();
1469
1470 if ($might_be_img) { # if this is actually an invalid link
1471 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1472 $found = false;
1473 while (isset ($a[$k+1]) ) {
1474 #look at the next 'line' to see if we can close it there
1475 $spliced = array_splice( $a, $k + 1, 1 );
1476 $next_line = array_shift( $spliced );
1477 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1478 # the first ]] closes the inner link, the second the image
1479 $found = true;
1480 $text .= '[[' . $m[1];
1481 $trail = $m[2];
1482 break;
1483 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1484 #if there's exactly one ]] that's fine, we'll keep looking
1485 $text .= '[[' . $m[0];
1486 } else {
1487 #if $next_line is invalid too, we need look no further
1488 $text .= '[[' . $next_line;
1489 break;
1490 }
1491 }
1492 if ( !$found ) {
1493 # we couldn't find the end of this imageLink, so output it raw
1494 #but don't ignore what might be perfectly normal links in the text we've examined
1495 $text = $this->replaceInternalLinks($text);
1496 $s .= $prefix . '[[' . $link . '|' . $text;
1497 # note: no $trail, because without an end, there *is* no trail
1498 continue;
1499 }
1500 } else { #it's not an image, so output it raw
1501 $s .= $prefix . '[[' . $link . '|' . $text;
1502 # note: no $trail, because without an end, there *is* no trail
1503 continue;
1504 }
1505 }
1506
1507 $wasblank = ( '' == $text );
1508 if( $wasblank ) $text = $link;
1509
1510
1511 # Link not escaped by : , create the various objects
1512 if( $noforce ) {
1513
1514 # Interwikis
1515 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1516 $this->mOutput->addLanguageLink( $nt->getFullText() );
1517 $s = rtrim($s . "\n");
1518 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1519 continue;
1520 }
1521
1522 if ( $ns == NS_IMAGE ) {
1523 wfProfileIn( "$fname-image" );
1524 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1525 # recursively parse links inside the image caption
1526 # actually, this will parse them in any other parameters, too,
1527 # but it might be hard to fix that, and it doesn't matter ATM
1528 $text = $this->replaceExternalLinks($text);
1529 $text = $this->replaceInternalLinks($text);
1530
1531 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1532 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1533 $this->mOutput->addImage( $nt->getDBkey() );
1534
1535 wfProfileOut( "$fname-image" );
1536 continue;
1537 }
1538 wfProfileOut( "$fname-image" );
1539
1540 }
1541
1542 if ( $ns == NS_CATEGORY ) {
1543 wfProfileIn( "$fname-category" );
1544 $s = rtrim($s . "\n"); # bug 87
1545
1546 if ( $wasblank ) {
1547 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1548 $sortkey = $this->mTitle->getText();
1549 } else {
1550 $sortkey = $this->mTitle->getPrefixedText();
1551 }
1552 } else {
1553 $sortkey = $text;
1554 }
1555 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1556 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1557 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1558
1559 /**
1560 * Strip the whitespace Category links produce, see bug 87
1561 * @todo We might want to use trim($tmp, "\n") here.
1562 */
1563 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1564
1565 wfProfileOut( "$fname-category" );
1566 continue;
1567 }
1568 }
1569
1570 if( ( $nt->getPrefixedText() === $selflink ) &&
1571 ( $nt->getFragment() === '' ) ) {
1572 # Self-links are handled specially; generally de-link and change to bold.
1573 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1574 continue;
1575 }
1576
1577 # Special and Media are pseudo-namespaces; no pages actually exist in them
1578 if( $ns == NS_MEDIA ) {
1579 $link = $sk->makeMediaLinkObj( $nt, $text );
1580 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1581 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1582 $this->mOutput->addImage( $nt->getDBkey() );
1583 continue;
1584 } elseif( $ns == NS_SPECIAL ) {
1585 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1586 continue;
1587 } elseif( $ns == NS_IMAGE ) {
1588 $img = Image::newFromTitle( $nt );
1589 if( $img->exists() ) {
1590 // Force a blue link if the file exists; may be a remote
1591 // upload on the shared repository, and we want to see its
1592 // auto-generated page.
1593 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1594 continue;
1595 }
1596 }
1597 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1598 }
1599 wfProfileOut( $fname );
1600 return $s;
1601 }
1602
1603 /**
1604 * Make a link placeholder. The text returned can be later resolved to a real link with
1605 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1606 * parsing of interwiki links, and secondly to allow all extistence checks and
1607 * article length checks (for stub links) to be bundled into a single query.
1608 *
1609 */
1610 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1611 if ( ! is_object($nt) ) {
1612 # Fail gracefully
1613 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1614 } else {
1615 # Separate the link trail from the rest of the link
1616 list( $inside, $trail ) = Linker::splitTrail( $trail );
1617
1618 if ( $nt->isExternal() ) {
1619 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1620 $this->mInterwikiLinkHolders['titles'][] = $nt;
1621 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1622 } else {
1623 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1624 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1625 $this->mLinkHolders['queries'][] = $query;
1626 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1627 $this->mLinkHolders['titles'][] = $nt;
1628
1629 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1630 }
1631 }
1632 return $retVal;
1633 }
1634
1635 /**
1636 * Render a forced-blue link inline; protect against double expansion of
1637 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1638 * Since this little disaster has to split off the trail text to avoid
1639 * breaking URLs in the following text without breaking trails on the
1640 * wiki links, it's been made into a horrible function.
1641 *
1642 * @param Title $nt
1643 * @param string $text
1644 * @param string $query
1645 * @param string $trail
1646 * @param string $prefix
1647 * @return string HTML-wikitext mix oh yuck
1648 */
1649 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1650 list( $inside, $trail ) = Linker::splitTrail( $trail );
1651 $sk =& $this->mOptions->getSkin();
1652 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1653 return $this->armorLinks( $link ) . $trail;
1654 }
1655
1656 /**
1657 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1658 * going to go through further parsing steps before inline URL expansion.
1659 *
1660 * In particular this is important when using action=render, which causes
1661 * full URLs to be included.
1662 *
1663 * Oh man I hate our multi-layer parser!
1664 *
1665 * @param string more-or-less HTML
1666 * @return string less-or-more HTML with NOPARSE bits
1667 */
1668 function armorLinks( $text ) {
1669 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1670 "{$this->mUniqPrefix}NOPARSE$1", $text );
1671 }
1672
1673 /**
1674 * Return true if subpage links should be expanded on this page.
1675 * @return bool
1676 */
1677 function areSubpagesAllowed() {
1678 # Some namespaces don't allow subpages
1679 global $wgNamespacesWithSubpages;
1680 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1681 }
1682
1683 /**
1684 * Handle link to subpage if necessary
1685 * @param string $target the source of the link
1686 * @param string &$text the link text, modified as necessary
1687 * @return string the full name of the link
1688 * @access private
1689 */
1690 function maybeDoSubpageLink($target, &$text) {
1691 # Valid link forms:
1692 # Foobar -- normal
1693 # :Foobar -- override special treatment of prefix (images, language links)
1694 # /Foobar -- convert to CurrentPage/Foobar
1695 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1696 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1697 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1698
1699 $fname = 'Parser::maybeDoSubpageLink';
1700 wfProfileIn( $fname );
1701 $ret = $target; # default return value is no change
1702
1703 # Some namespaces don't allow subpages,
1704 # so only perform processing if subpages are allowed
1705 if( $this->areSubpagesAllowed() ) {
1706 # Look at the first character
1707 if( $target != '' && $target{0} == '/' ) {
1708 # / at end means we don't want the slash to be shown
1709 if( substr( $target, -1, 1 ) == '/' ) {
1710 $target = substr( $target, 1, -1 );
1711 $noslash = $target;
1712 } else {
1713 $noslash = substr( $target, 1 );
1714 }
1715
1716 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1717 if( '' === $text ) {
1718 $text = $target;
1719 } # this might be changed for ugliness reasons
1720 } else {
1721 # check for .. subpage backlinks
1722 $dotdotcount = 0;
1723 $nodotdot = $target;
1724 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1725 ++$dotdotcount;
1726 $nodotdot = substr( $nodotdot, 3 );
1727 }
1728 if($dotdotcount > 0) {
1729 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1730 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1731 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1732 # / at the end means don't show full path
1733 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1734 $nodotdot = substr( $nodotdot, 0, -1 );
1735 if( '' === $text ) {
1736 $text = $nodotdot;
1737 }
1738 }
1739 $nodotdot = trim( $nodotdot );
1740 if( $nodotdot != '' ) {
1741 $ret .= '/' . $nodotdot;
1742 }
1743 }
1744 }
1745 }
1746 }
1747
1748 wfProfileOut( $fname );
1749 return $ret;
1750 }
1751
1752 /**#@+
1753 * Used by doBlockLevels()
1754 * @access private
1755 */
1756 /* private */ function closeParagraph() {
1757 $result = '';
1758 if ( '' != $this->mLastSection ) {
1759 $result = '</' . $this->mLastSection . ">\n";
1760 }
1761 $this->mInPre = false;
1762 $this->mLastSection = '';
1763 return $result;
1764 }
1765 # getCommon() returns the length of the longest common substring
1766 # of both arguments, starting at the beginning of both.
1767 #
1768 /* private */ function getCommon( $st1, $st2 ) {
1769 $fl = strlen( $st1 );
1770 $shorter = strlen( $st2 );
1771 if ( $fl < $shorter ) { $shorter = $fl; }
1772
1773 for ( $i = 0; $i < $shorter; ++$i ) {
1774 if ( $st1{$i} != $st2{$i} ) { break; }
1775 }
1776 return $i;
1777 }
1778 # These next three functions open, continue, and close the list
1779 # element appropriate to the prefix character passed into them.
1780 #
1781 /* private */ function openList( $char ) {
1782 $result = $this->closeParagraph();
1783
1784 if ( '*' == $char ) { $result .= '<ul><li>'; }
1785 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1786 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1787 else if ( ';' == $char ) {
1788 $result .= '<dl><dt>';
1789 $this->mDTopen = true;
1790 }
1791 else { $result = '<!-- ERR 1 -->'; }
1792
1793 return $result;
1794 }
1795
1796 /* private */ function nextItem( $char ) {
1797 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1798 else if ( ':' == $char || ';' == $char ) {
1799 $close = '</dd>';
1800 if ( $this->mDTopen ) { $close = '</dt>'; }
1801 if ( ';' == $char ) {
1802 $this->mDTopen = true;
1803 return $close . '<dt>';
1804 } else {
1805 $this->mDTopen = false;
1806 return $close . '<dd>';
1807 }
1808 }
1809 return '<!-- ERR 2 -->';
1810 }
1811
1812 /* private */ function closeList( $char ) {
1813 if ( '*' == $char ) { $text = '</li></ul>'; }
1814 else if ( '#' == $char ) { $text = '</li></ol>'; }
1815 else if ( ':' == $char ) {
1816 if ( $this->mDTopen ) {
1817 $this->mDTopen = false;
1818 $text = '</dt></dl>';
1819 } else {
1820 $text = '</dd></dl>';
1821 }
1822 }
1823 else { return '<!-- ERR 3 -->'; }
1824 return $text."\n";
1825 }
1826 /**#@-*/
1827
1828 /**
1829 * Make lists from lines starting with ':', '*', '#', etc.
1830 *
1831 * @access private
1832 * @return string the lists rendered as HTML
1833 */
1834 function doBlockLevels( $text, $linestart ) {
1835 $fname = 'Parser::doBlockLevels';
1836 wfProfileIn( $fname );
1837
1838 # Parsing through the text line by line. The main thing
1839 # happening here is handling of block-level elements p, pre,
1840 # and making lists from lines starting with * # : etc.
1841 #
1842 $textLines = explode( "\n", $text );
1843
1844 $lastPrefix = $output = '';
1845 $this->mDTopen = $inBlockElem = false;
1846 $prefixLength = 0;
1847 $paragraphStack = false;
1848
1849 if ( !$linestart ) {
1850 $output .= array_shift( $textLines );
1851 }
1852 foreach ( $textLines as $oLine ) {
1853 $lastPrefixLength = strlen( $lastPrefix );
1854 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1855 $preOpenMatch = preg_match('/<pre/i', $oLine );
1856 if ( !$this->mInPre ) {
1857 # Multiple prefixes may abut each other for nested lists.
1858 $prefixLength = strspn( $oLine, '*#:;' );
1859 $pref = substr( $oLine, 0, $prefixLength );
1860
1861 # eh?
1862 $pref2 = str_replace( ';', ':', $pref );
1863 $t = substr( $oLine, $prefixLength );
1864 $this->mInPre = !empty($preOpenMatch);
1865 } else {
1866 # Don't interpret any other prefixes in preformatted text
1867 $prefixLength = 0;
1868 $pref = $pref2 = '';
1869 $t = $oLine;
1870 }
1871
1872 # List generation
1873 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1874 # Same as the last item, so no need to deal with nesting or opening stuff
1875 $output .= $this->nextItem( substr( $pref, -1 ) );
1876 $paragraphStack = false;
1877
1878 if ( substr( $pref, -1 ) == ';') {
1879 # The one nasty exception: definition lists work like this:
1880 # ; title : definition text
1881 # So we check for : in the remainder text to split up the
1882 # title and definition, without b0rking links.
1883 $term = $t2 = '';
1884 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1885 $t = $t2;
1886 $output .= $term . $this->nextItem( ':' );
1887 }
1888 }
1889 } elseif( $prefixLength || $lastPrefixLength ) {
1890 # Either open or close a level...
1891 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1892 $paragraphStack = false;
1893
1894 while( $commonPrefixLength < $lastPrefixLength ) {
1895 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1896 --$lastPrefixLength;
1897 }
1898 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1899 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1900 }
1901 while ( $prefixLength > $commonPrefixLength ) {
1902 $char = substr( $pref, $commonPrefixLength, 1 );
1903 $output .= $this->openList( $char );
1904
1905 if ( ';' == $char ) {
1906 # FIXME: This is dupe of code above
1907 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1908 $t = $t2;
1909 $output .= $term . $this->nextItem( ':' );
1910 }
1911 }
1912 ++$commonPrefixLength;
1913 }
1914 $lastPrefix = $pref2;
1915 }
1916 if( 0 == $prefixLength ) {
1917 wfProfileIn( "$fname-paragraph" );
1918 # No prefix (not in list)--go to paragraph mode
1919 // XXX: use a stack for nestable elements like span, table and div
1920 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1921 $closematch = preg_match(
1922 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1923 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1924 if ( $openmatch or $closematch ) {
1925 $paragraphStack = false;
1926 $output .= $this->closeParagraph();
1927 if ( $preOpenMatch and !$preCloseMatch ) {
1928 $this->mInPre = true;
1929 }
1930 if ( $closematch ) {
1931 $inBlockElem = false;
1932 } else {
1933 $inBlockElem = true;
1934 }
1935 } else if ( !$inBlockElem && !$this->mInPre ) {
1936 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1937 // pre
1938 if ($this->mLastSection != 'pre') {
1939 $paragraphStack = false;
1940 $output .= $this->closeParagraph().'<pre>';
1941 $this->mLastSection = 'pre';
1942 }
1943 $t = substr( $t, 1 );
1944 } else {
1945 // paragraph
1946 if ( '' == trim($t) ) {
1947 if ( $paragraphStack ) {
1948 $output .= $paragraphStack.'<br />';
1949 $paragraphStack = false;
1950 $this->mLastSection = 'p';
1951 } else {
1952 if ($this->mLastSection != 'p' ) {
1953 $output .= $this->closeParagraph();
1954 $this->mLastSection = '';
1955 $paragraphStack = '<p>';
1956 } else {
1957 $paragraphStack = '</p><p>';
1958 }
1959 }
1960 } else {
1961 if ( $paragraphStack ) {
1962 $output .= $paragraphStack;
1963 $paragraphStack = false;
1964 $this->mLastSection = 'p';
1965 } else if ($this->mLastSection != 'p') {
1966 $output .= $this->closeParagraph().'<p>';
1967 $this->mLastSection = 'p';
1968 }
1969 }
1970 }
1971 }
1972 wfProfileOut( "$fname-paragraph" );
1973 }
1974 // somewhere above we forget to get out of pre block (bug 785)
1975 if($preCloseMatch && $this->mInPre) {
1976 $this->mInPre = false;
1977 }
1978 if ($paragraphStack === false) {
1979 $output .= $t."\n";
1980 }
1981 }
1982 while ( $prefixLength ) {
1983 $output .= $this->closeList( $pref2{$prefixLength-1} );
1984 --$prefixLength;
1985 }
1986 if ( '' != $this->mLastSection ) {
1987 $output .= '</' . $this->mLastSection . '>';
1988 $this->mLastSection = '';
1989 }
1990
1991 wfProfileOut( $fname );
1992 return $output;
1993 }
1994
1995 /**
1996 * Split up a string on ':', ignoring any occurences inside
1997 * <a>..</a> or <span>...</span>
1998 * @param string $str the string to split
1999 * @param string &$before set to everything before the ':'
2000 * @param string &$after set to everything after the ':'
2001 * return string the position of the ':', or false if none found
2002 */
2003 function findColonNoLinks($str, &$before, &$after) {
2004 # I wonder if we should make this count all tags, not just <a>
2005 # and <span>. That would prevent us from matching a ':' that
2006 # comes in the middle of italics other such formatting....
2007 # -- Wil
2008 $fname = 'Parser::findColonNoLinks';
2009 wfProfileIn( $fname );
2010 $pos = 0;
2011 do {
2012 $colon = strpos($str, ':', $pos);
2013
2014 if ($colon !== false) {
2015 $before = substr($str, 0, $colon);
2016 $after = substr($str, $colon + 1);
2017
2018 # Skip any ':' within <a> or <span> pairs
2019 $a = substr_count($before, '<a');
2020 $s = substr_count($before, '<span');
2021 $ca = substr_count($before, '</a>');
2022 $cs = substr_count($before, '</span>');
2023
2024 if ($a <= $ca and $s <= $cs) {
2025 # Tags are balanced before ':'; ok
2026 break;
2027 }
2028 $pos = $colon + 1;
2029 }
2030 } while ($colon !== false);
2031 wfProfileOut( $fname );
2032 return $colon;
2033 }
2034
2035 /**
2036 * Return value of a magic variable (like PAGENAME)
2037 *
2038 * @access private
2039 */
2040 function getVariableValue( $index ) {
2041 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2042
2043 /**
2044 * Some of these require message or data lookups and can be
2045 * expensive to check many times.
2046 */
2047 static $varCache = array();
2048 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2049 if ( isset( $varCache[$index] ) )
2050 return $varCache[$index];
2051
2052 $ts = time();
2053 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2054
2055 switch ( $index ) {
2056 case MAG_CURRENTMONTH:
2057 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2058 case MAG_CURRENTMONTHNAME:
2059 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2060 case MAG_CURRENTMONTHNAMEGEN:
2061 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2062 case MAG_CURRENTMONTHABBREV:
2063 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2064 case MAG_CURRENTDAY:
2065 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2066 case MAG_CURRENTDAY2:
2067 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2068 case MAG_PAGENAME:
2069 return $this->mTitle->getText();
2070 case MAG_PAGENAMEE:
2071 return $this->mTitle->getPartialURL();
2072 case MAG_FULLPAGENAME:
2073 return $this->mTitle->getPrefixedText();
2074 case MAG_FULLPAGENAMEE:
2075 return $this->mTitle->getPrefixedURL();
2076 case MAG_SUBPAGENAME:
2077 return $this->mTitle->getSubpageText();
2078 case MAG_REVISIONID:
2079 return $this->mRevisionId;
2080 case MAG_NAMESPACE:
2081 return $wgContLang->getNsText( $this->mTitle->getNamespace() );
2082 case MAG_NAMESPACEE:
2083 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2084 case MAG_CURRENTDAYNAME:
2085 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) + 1 );
2086 case MAG_CURRENTYEAR:
2087 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2088 case MAG_CURRENTTIME:
2089 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2090 case MAG_CURRENTWEEK:
2091 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2092 // int to remove the padding
2093 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2094 case MAG_CURRENTDOW:
2095 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2096 case MAG_NUMBEROFARTICLES:
2097 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2098 case MAG_NUMBEROFFILES:
2099 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2100 case MAG_SITENAME:
2101 return $wgSitename;
2102 case MAG_SERVER:
2103 return $wgServer;
2104 case MAG_SERVERNAME:
2105 return $wgServerName;
2106 case MAG_SCRIPTPATH:
2107 return $wgScriptPath;
2108 default:
2109 $ret = null;
2110 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2111 return $ret;
2112 else
2113 return null;
2114 }
2115 }
2116
2117 /**
2118 * initialise the magic variables (like CURRENTMONTHNAME)
2119 *
2120 * @access private
2121 */
2122 function initialiseVariables() {
2123 $fname = 'Parser::initialiseVariables';
2124 wfProfileIn( $fname );
2125 global $wgVariableIDs;
2126 $this->mVariables = array();
2127 foreach ( $wgVariableIDs as $id ) {
2128 $mw =& MagicWord::get( $id );
2129 $mw->addToArray( $this->mVariables, $id );
2130 }
2131 wfProfileOut( $fname );
2132 }
2133
2134 /**
2135 * parse any parentheses in format ((title|part|part))
2136 * and call callbacks to get a replacement text for any found piece
2137 *
2138 * @param string $text The text to parse
2139 * @param array $callbacks rules in form:
2140 * '{' => array( # opening parentheses
2141 * 'end' => '}', # closing parentheses
2142 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2143 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2144 * )
2145 * )
2146 * @access private
2147 */
2148 function replace_callback ($text, $callbacks) {
2149 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2150 $lastOpeningBrace = -1; # last not closed parentheses
2151
2152 for ($i = 0; $i < strlen($text); $i++) {
2153 # check for any opening brace
2154 $rule = null;
2155 $nextPos = -1;
2156 foreach ($callbacks as $key => $value) {
2157 $pos = strpos ($text, $key, $i);
2158 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)) {
2159 $rule = $value;
2160 $nextPos = $pos;
2161 }
2162 }
2163
2164 if ($lastOpeningBrace >= 0) {
2165 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2166
2167 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2168 $rule = null;
2169 $nextPos = $pos;
2170 }
2171
2172 $pos = strpos ($text, '|', $i);
2173
2174 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2175 $rule = null;
2176 $nextPos = $pos;
2177 }
2178 }
2179
2180 if ($nextPos == -1)
2181 break;
2182
2183 $i = $nextPos;
2184
2185 # found openning brace, lets add it to parentheses stack
2186 if (null != $rule) {
2187 $piece = array('brace' => $text[$i],
2188 'braceEnd' => $rule['end'],
2189 'count' => 1,
2190 'title' => '',
2191 'parts' => null);
2192
2193 # count openning brace characters
2194 while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
2195 $piece['count']++;
2196 $i++;
2197 }
2198
2199 $piece['startAt'] = $i+1;
2200 $piece['partStart'] = $i+1;
2201
2202 # we need to add to stack only if openning brace count is enough for any given rule
2203 foreach ($rule['cb'] as $cnt => $fn) {
2204 if ($piece['count'] >= $cnt) {
2205 $lastOpeningBrace ++;
2206 $openingBraceStack[$lastOpeningBrace] = $piece;
2207 break;
2208 }
2209 }
2210
2211 continue;
2212 }
2213 else if ($lastOpeningBrace >= 0) {
2214 # first check if it is a closing brace
2215 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2216 # lets check if it is enough characters for closing brace
2217 $count = 1;
2218 while ($i+$count < strlen($text) && $text[$i+$count] == $text[$i])
2219 $count++;
2220
2221 # if there are more closing parentheses than opening ones, we parse less
2222 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2223 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2224
2225 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2226 $matchingCount = 0;
2227 $matchingCallback = null;
2228 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2229 if ($count >= $cnt && $matchingCount < $cnt) {
2230 $matchingCount = $cnt;
2231 $matchingCallback = $fn;
2232 }
2233 }
2234
2235 if ($matchingCount == 0) {
2236 $i += $count - 1;
2237 continue;
2238 }
2239
2240 # lets set a title or last part (if '|' was found)
2241 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2242 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2243 else
2244 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2245
2246 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2247 $pieceEnd = $i + $matchingCount;
2248
2249 if( is_callable( $matchingCallback ) ) {
2250 $cbArgs = array (
2251 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2252 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2253 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2254 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2255 );
2256 # finally we can call a user callback and replace piece of text
2257 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2258 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2259 $i = $pieceStart + strlen($replaceWith) - 1;
2260 }
2261 else {
2262 # null value for callback means that parentheses should be parsed, but not replaced
2263 $i += $matchingCount - 1;
2264 }
2265
2266 # reset last openning parentheses, but keep it in case there are unused characters
2267 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2268 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2269 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2270 'title' => '',
2271 'parts' => null,
2272 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2273 $openingBraceStack[$lastOpeningBrace--] = null;
2274
2275 if ($matchingCount < $piece['count']) {
2276 $piece['count'] -= $matchingCount;
2277 $piece['startAt'] -= $matchingCount;
2278 $piece['partStart'] = $piece['startAt'];
2279 # do we still qualify for any callback with remaining count?
2280 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2281 if ($piece['count'] >= $cnt) {
2282 $lastOpeningBrace ++;
2283 $openingBraceStack[$lastOpeningBrace] = $piece;
2284 break;
2285 }
2286 }
2287 }
2288 continue;
2289 }
2290
2291 # lets set a title if it is a first separator, or next part otherwise
2292 if ($text[$i] == '|') {
2293 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2294 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2295 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2296 }
2297 else
2298 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2299
2300 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
2301 }
2302 }
2303 }
2304
2305 return $text;
2306 }
2307
2308 /**
2309 * Replace magic variables, templates, and template arguments
2310 * with the appropriate text. Templates are substituted recursively,
2311 * taking care to avoid infinite loops.
2312 *
2313 * Note that the substitution depends on value of $mOutputType:
2314 * OT_WIKI: only {{subst:}} templates
2315 * OT_MSG: only magic variables
2316 * OT_HTML: all templates and magic variables
2317 *
2318 * @param string $tex The text to transform
2319 * @param array $args Key-value pairs representing template parameters to substitute
2320 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2321 * @access private
2322 */
2323 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2324 # Prevent too big inclusions
2325 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
2326 return $text;
2327 }
2328
2329 $fname = 'Parser::replaceVariables';
2330 wfProfileIn( $fname );
2331
2332 # This function is called recursively. To keep track of arguments we need a stack:
2333 array_push( $this->mArgStack, $args );
2334
2335 $braceCallbacks = array();
2336 if ( !$argsOnly ) {
2337 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2338 }
2339 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
2340 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2341 }
2342 $callbacks = array();
2343 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2344 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2345 $text = $this->replace_callback ($text, $callbacks);
2346
2347 array_pop( $this->mArgStack );
2348
2349 wfProfileOut( $fname );
2350 return $text;
2351 }
2352
2353 /**
2354 * Replace magic variables
2355 * @access private
2356 */
2357 function variableSubstitution( $matches ) {
2358 $fname = 'Parser::variableSubstitution';
2359 $varname = $matches[1];
2360 wfProfileIn( $fname );
2361 if ( !$this->mVariables ) {
2362 $this->initialiseVariables();
2363 }
2364 $skip = false;
2365 if ( $this->mOutputType == OT_WIKI ) {
2366 # Do only magic variables prefixed by SUBST
2367 $mwSubst =& MagicWord::get( MAG_SUBST );
2368 if (!$mwSubst->matchStartAndRemove( $varname ))
2369 $skip = true;
2370 # Note that if we don't substitute the variable below,
2371 # we don't remove the {{subst:}} magic word, in case
2372 # it is a template rather than a magic variable.
2373 }
2374 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2375 $id = $this->mVariables[$varname];
2376 $text = $this->getVariableValue( $id );
2377 $this->mOutput->mContainsOldMagic = true;
2378 } else {
2379 $text = $matches[0];
2380 }
2381 wfProfileOut( $fname );
2382 return $text;
2383 }
2384
2385 # Split template arguments
2386 function getTemplateArgs( $argsString ) {
2387 if ( $argsString === '' ) {
2388 return array();
2389 }
2390
2391 $args = explode( '|', substr( $argsString, 1 ) );
2392
2393 # If any of the arguments contains a '[[' but no ']]', it needs to be
2394 # merged with the next arg because the '|' character between belongs
2395 # to the link syntax and not the template parameter syntax.
2396 $argc = count($args);
2397
2398 for ( $i = 0; $i < $argc-1; $i++ ) {
2399 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2400 $args[$i] .= '|'.$args[$i+1];
2401 array_splice($args, $i+1, 1);
2402 $i--;
2403 $argc--;
2404 }
2405 }
2406
2407 return $args;
2408 }
2409
2410 /**
2411 * Return the text of a template, after recursively
2412 * replacing any variables or templates within the template.
2413 *
2414 * @param array $piece The parts of the template
2415 * $piece['text']: matched text
2416 * $piece['title']: the title, i.e. the part before the |
2417 * $piece['parts']: the parameter array
2418 * @return string the text of the template
2419 * @access private
2420 */
2421 function braceSubstitution( $piece ) {
2422 global $wgContLang;
2423 $fname = 'Parser::braceSubstitution';
2424 wfProfileIn( $fname );
2425
2426 # Flags
2427 $found = false; # $text has been filled
2428 $nowiki = false; # wiki markup in $text should be escaped
2429 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2430 $noargs = false; # Don't replace triple-brace arguments in $text
2431 $replaceHeadings = false; # Make the edit section links go to the template not the article
2432 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2433 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2434
2435 # Title object, where $text came from
2436 $title = NULL;
2437
2438 $linestart = '';
2439
2440 # $part1 is the bit before the first |, and must contain only title characters
2441 # $args is a list of arguments, starting from index 0, not including $part1
2442
2443 $part1 = $piece['title'];
2444 # If the third subpattern matched anything, it will start with |
2445
2446 if (null == $piece['parts']) {
2447 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2448 if ($replaceWith != $piece['text']) {
2449 $text = $replaceWith;
2450 $found = true;
2451 $noparse = true;
2452 $noargs = true;
2453 }
2454 }
2455
2456 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2457 $argc = count( $args );
2458
2459 # SUBST
2460 if ( !$found ) {
2461 $mwSubst =& MagicWord::get( MAG_SUBST );
2462 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2463 # One of two possibilities is true:
2464 # 1) Found SUBST but not in the PST phase
2465 # 2) Didn't find SUBST and in the PST phase
2466 # In either case, return without further processing
2467 $text = $piece['text'];
2468 $found = true;
2469 $noparse = true;
2470 $noargs = true;
2471 }
2472 }
2473
2474 # MSG, MSGNW, INT and RAW
2475 if ( !$found ) {
2476 # Check for MSGNW:
2477 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2478 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2479 $nowiki = true;
2480 } else {
2481 # Remove obsolete MSG:
2482 $mwMsg =& MagicWord::get( MAG_MSG );
2483 $mwMsg->matchStartAndRemove( $part1 );
2484 }
2485
2486 # Check for RAW:
2487 $mwRaw =& MagicWord::get( MAG_RAW );
2488 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2489 $forceRawInterwiki = true;
2490 }
2491
2492 # Check if it is an internal message
2493 $mwInt =& MagicWord::get( MAG_INT );
2494 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2495 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2496 $text = $linestart . wfMsgReal( $part1, $args, true );
2497 $found = true;
2498 }
2499 }
2500 }
2501
2502 # NS
2503 if ( !$found ) {
2504 # Check for NS: (namespace expansion)
2505 $mwNs = MagicWord::get( MAG_NS );
2506 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2507 if ( intval( $part1 ) || $part1 == "0" ) {
2508 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2509 $found = true;
2510 } else {
2511 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2512 if ( !is_null( $index ) ) {
2513 $text = $linestart . $wgContLang->getNsText( $index );
2514 $found = true;
2515 }
2516 }
2517 }
2518 }
2519
2520 # LCFIRST, UCFIRST, LC and UC
2521 if ( !$found ) {
2522 $lcfirst =& MagicWord::get( MAG_LCFIRST );
2523 $ucfirst =& MagicWord::get( MAG_UCFIRST );
2524 $lc =& MagicWord::get( MAG_LC );
2525 $uc =& MagicWord::get( MAG_UC );
2526 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2527 $text = $linestart . $wgContLang->lcfirst( $part1 );
2528 $found = true;
2529 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2530 $text = $linestart . $wgContLang->ucfirst( $part1 );
2531 $found = true;
2532 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2533 $text = $linestart . $wgContLang->lc( $part1 );
2534 $found = true;
2535 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2536 $text = $linestart . $wgContLang->uc( $part1 );
2537 $found = true;
2538 }
2539 }
2540
2541 # LOCALURL and FULLURL
2542 if ( !$found ) {
2543 $mwLocal =& MagicWord::get( MAG_LOCALURL );
2544 $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
2545 $mwFull =& MagicWord::get( MAG_FULLURL );
2546 $mwFullE =& MagicWord::get( MAG_FULLURLE );
2547
2548
2549 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2550 $func = 'getLocalURL';
2551 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2552 $func = 'escapeLocalURL';
2553 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2554 $func = 'getFullURL';
2555 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2556 $func = 'escapeFullURL';
2557 } else {
2558 $func = false;
2559 }
2560
2561 if ( $func !== false ) {
2562 $title = Title::newFromText( $part1 );
2563 if ( !is_null( $title ) ) {
2564 if ( $argc > 0 ) {
2565 $text = $linestart . $title->$func( $args[0] );
2566 } else {
2567 $text = $linestart . $title->$func();
2568 }
2569 $found = true;
2570 }
2571 }
2572 }
2573
2574 # GRAMMAR
2575 if ( !$found && $argc == 1 ) {
2576 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2577 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2578 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2579 $found = true;
2580 }
2581 }
2582
2583 # PLURAL
2584 if ( !$found && $argc >= 2 ) {
2585 $mwPluralForm =& MagicWord::get( MAG_PLURAL );
2586 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2587 if ($argc==2) {$args[2]=$args[1];}
2588 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2589 $found = true;
2590 }
2591 }
2592
2593 # Template table test
2594
2595 # Did we encounter this template already? If yes, it is in the cache
2596 # and we need to check for loops.
2597 if ( !$found && isset( $this->mTemplates[$piece['title']] ) ) {
2598 $found = true;
2599
2600 # Infinite loop test
2601 if ( isset( $this->mTemplatePath[$part1] ) ) {
2602 $noparse = true;
2603 $noargs = true;
2604 $found = true;
2605 $text = $linestart .
2606 '{{' . $part1 . '}}' .
2607 '<!-- WARNING: template loop detected -->';
2608 wfDebug( "$fname: template loop broken at '$part1'\n" );
2609 } else {
2610 # set $text to cached message.
2611 $text = $linestart . $this->mTemplates[$piece['title']];
2612 }
2613 }
2614
2615 # Load from database
2616 $lastPathLevel = $this->mTemplatePath;
2617 if ( !$found ) {
2618 $ns = NS_TEMPLATE;
2619 # declaring $subpage directly in the function call
2620 # does not work correctly with references and breaks
2621 # {{/subpage}}-style inclusions
2622 $subpage = '';
2623 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2624 if ($subpage !== '') {
2625 $ns = $this->mTitle->getNamespace();
2626 }
2627 $title = Title::newFromText( $part1, $ns );
2628
2629 if ( !is_null( $title ) ) {
2630 if ( !$title->isExternal() ) {
2631 # Check for excessive inclusion
2632 $dbk = $title->getPrefixedDBkey();
2633 if ( $this->incrementIncludeCount( $dbk ) ) {
2634 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() ) {
2635 # Capture special page output
2636 $text = SpecialPage::capturePath( $title );
2637 if ( is_string( $text ) ) {
2638 $found = true;
2639 $noparse = true;
2640 $noargs = true;
2641 $isHTML = true;
2642 $this->disableCache();
2643 }
2644 } else {
2645 $articleContent = $this->fetchTemplate( $title );
2646 if ( $articleContent !== false ) {
2647 $found = true;
2648 $text = $articleContent;
2649 $replaceHeadings = true;
2650 }
2651 }
2652 }
2653
2654 # If the title is valid but undisplayable, make a link to it
2655 if ( $this->mOutputType == OT_HTML && !$found ) {
2656 $text = '[['.$title->getPrefixedText().']]';
2657 $found = true;
2658 }
2659 } elseif ( $title->isTrans() ) {
2660 // Interwiki transclusion
2661 if ( $this->mOutputType == OT_HTML && !$forceRawInterwiki ) {
2662 $text = $this->interwikiTransclude( $title, 'render' );
2663 $isHTML = true;
2664 $noparse = true;
2665 } else {
2666 $text = $this->interwikiTransclude( $title, 'raw' );
2667 $replaceHeadings = true;
2668 }
2669 $found = true;
2670 }
2671
2672 # Template cache array insertion
2673 # Use the original $piece['title'] not the mangled $part1, so that
2674 # modifiers such as RAW: produce separate cache entries
2675 if( $found ) {
2676 $this->mTemplates[$piece['title']] = $text;
2677 $text = $linestart . $text;
2678 }
2679 }
2680 }
2681
2682 # Recursive parsing, escaping and link table handling
2683 # Only for HTML output
2684 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2685 $text = wfEscapeWikiText( $text );
2686 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found ) {
2687 if ( !$noargs ) {
2688 # Clean up argument array
2689 $assocArgs = array();
2690 $index = 1;
2691 foreach( $args as $arg ) {
2692 $eqpos = strpos( $arg, '=' );
2693 if ( $eqpos === false ) {
2694 $assocArgs[$index++] = $arg;
2695 } else {
2696 $name = trim( substr( $arg, 0, $eqpos ) );
2697 $value = trim( substr( $arg, $eqpos+1 ) );
2698 if ( $value === false ) {
2699 $value = '';
2700 }
2701 if ( $name !== false ) {
2702 $assocArgs[$name] = $value;
2703 }
2704 }
2705 }
2706
2707 # Add a new element to the templace recursion path
2708 $this->mTemplatePath[$part1] = 1;
2709 }
2710
2711 if ( !$noparse ) {
2712 # If there are any <onlyinclude> tags, only include them
2713 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2714 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2715 $text = '';
2716 foreach ($m[1] as $piece)
2717 $text .= $piece;
2718 }
2719 # Remove <noinclude> sections and <includeonly> tags
2720 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2721 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2722
2723 if( $this->mOutputType == OT_HTML ) {
2724 # Strip <nowiki>, <pre>, etc.
2725 $text = $this->strip( $text, $this->mStripState );
2726 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2727 }
2728 $text = $this->replaceVariables( $text, $assocArgs );
2729
2730 # If the template begins with a table or block-level
2731 # element, it should be treated as beginning a new line.
2732 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2733 $text = "\n" . $text;
2734 }
2735 } elseif ( !$noargs ) {
2736 # $noparse and !$noargs
2737 # Just replace the arguments, not any double-brace items
2738 # This is used for rendered interwiki transclusion
2739 $text = $this->replaceVariables( $text, $assocArgs, true );
2740 }
2741 }
2742 # Prune lower levels off the recursion check path
2743 $this->mTemplatePath = $lastPathLevel;
2744
2745 if ( !$found ) {
2746 wfProfileOut( $fname );
2747 return $piece['text'];
2748 } else {
2749 if ( $isHTML ) {
2750 # Replace raw HTML by a placeholder
2751 # Add a blank line preceding, to prevent it from mucking up
2752 # immediately preceding headings
2753 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
2754 } else {
2755 # replace ==section headers==
2756 # XXX this needs to go away once we have a better parser.
2757 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
2758 if( !is_null( $title ) )
2759 $encodedname = base64_encode($title->getPrefixedDBkey());
2760 else
2761 $encodedname = base64_encode("");
2762 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2763 PREG_SPLIT_DELIM_CAPTURE);
2764 $text = '';
2765 $nsec = 0;
2766 for( $i = 0; $i < count($m); $i += 2 ) {
2767 $text .= $m[$i];
2768 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2769 $hl = $m[$i + 1];
2770 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2771 $text .= $hl;
2772 continue;
2773 }
2774 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2775 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2776 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2777
2778 $nsec++;
2779 }
2780 }
2781 }
2782 }
2783
2784 # Prune lower levels off the recursion check path
2785 $this->mTemplatePath = $lastPathLevel;
2786
2787 if ( !$found ) {
2788 wfProfileOut( $fname );
2789 return $piece['text'];
2790 } else {
2791 wfProfileOut( $fname );
2792 return $text;
2793 }
2794 }
2795
2796 /**
2797 * Fetch the unparsed text of a template and register a reference to it.
2798 */
2799 function fetchTemplate( $title ) {
2800 $text = false;
2801 // Loop to fetch the article, with up to 1 redirect
2802 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
2803 $rev = Revision::newFromTitle( $title );
2804 $this->mOutput->addTemplate( $title, $title->getArticleID() );
2805 if ( !$rev ) {
2806 break;
2807 }
2808 $text = $rev->getText();
2809 if ( $text === false ) {
2810 break;
2811 }
2812 // Redirect?
2813 $title = Title::newFromRedirect( $text );
2814 }
2815 return $text;
2816 }
2817
2818 /**
2819 * Transclude an interwiki link.
2820 */
2821 function interwikiTransclude( $title, $action ) {
2822 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2823
2824 if (!$wgEnableScaryTranscluding)
2825 return wfMsg('scarytranscludedisabled');
2826
2827 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2828 // But we'll handle it generally anyway
2829 if ( $title->getNamespace() ) {
2830 // Use the canonical namespace, which should work anywhere
2831 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2832 } else {
2833 $articleName = $title->getDBkey();
2834 }
2835
2836 $url = str_replace('$1', urlencode($articleName), Title::getInterwikiLink($title->getInterwiki()));
2837 $url .= "?action=$action";
2838 if (strlen($url) > 255)
2839 return wfMsg('scarytranscludetoolong');
2840 return $this->fetchScaryTemplateMaybeFromCache($url);
2841 }
2842
2843 function fetchScaryTemplateMaybeFromCache($url) {
2844 global $wgTranscludeCacheExpiry;
2845 $dbr =& wfGetDB(DB_SLAVE);
2846 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2847 array('tc_url' => $url));
2848 if ($obj) {
2849 $time = $obj->tc_time;
2850 $text = $obj->tc_contents;
2851 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
2852 return $text;
2853 }
2854 }
2855
2856 $text = wfGetHTTP($url);
2857 if (!$text)
2858 return wfMsg('scarytranscludefailed', $url);
2859
2860 $dbw =& wfGetDB(DB_MASTER);
2861 $dbw->replace('transcache', array('tc_url'), array(
2862 'tc_url' => $url,
2863 'tc_time' => time(),
2864 'tc_contents' => $text));
2865 return $text;
2866 }
2867
2868
2869 /**
2870 * Triple brace replacement -- used for template arguments
2871 * @access private
2872 */
2873 function argSubstitution( $matches ) {
2874 $arg = trim( $matches['title'] );
2875 $text = $matches['text'];
2876 $inputArgs = end( $this->mArgStack );
2877
2878 if ( array_key_exists( $arg, $inputArgs ) ) {
2879 $text = $inputArgs[$arg];
2880 } else if ($this->mOutputType == OT_HTML && null != $matches['parts'] && count($matches['parts']) > 0) {
2881 $text = $matches['parts'][0];
2882 }
2883
2884 return $text;
2885 }
2886
2887 /**
2888 * Returns true if the function is allowed to include this entity
2889 * @access private
2890 */
2891 function incrementIncludeCount( $dbk ) {
2892 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2893 $this->mIncludeCount[$dbk] = 0;
2894 }
2895 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2896 return true;
2897 } else {
2898 return false;
2899 }
2900 }
2901
2902 /**
2903 * This function accomplishes several tasks:
2904 * 1) Auto-number headings if that option is enabled
2905 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2906 * 3) Add a Table of contents on the top for users who have enabled the option
2907 * 4) Auto-anchor headings
2908 *
2909 * It loops through all headlines, collects the necessary data, then splits up the
2910 * string and re-inserts the newly formatted headlines.
2911 *
2912 * @param string $text
2913 * @param boolean $isMain
2914 * @access private
2915 */
2916 function formatHeadings( $text, $isMain=true ) {
2917 global $wgMaxTocLevel, $wgContLang;
2918
2919 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2920 $doShowToc = true;
2921 $forceTocHere = false;
2922 if( !$this->mTitle->userCanEdit() ) {
2923 $showEditLink = 0;
2924 } else {
2925 $showEditLink = $this->mOptions->getEditSection();
2926 }
2927
2928 # Inhibit editsection links if requested in the page
2929 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2930 if( $esw->matchAndRemove( $text ) ) {
2931 $showEditLink = 0;
2932 }
2933 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2934 # do not add TOC
2935 $mw =& MagicWord::get( MAG_NOTOC );
2936 if( $mw->matchAndRemove( $text ) ) {
2937 $doShowToc = false;
2938 }
2939
2940 # Get all headlines for numbering them and adding funky stuff like [edit]
2941 # links - this is for later, but we need the number of headlines right now
2942 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2943
2944 # if there are fewer than 4 headlines in the article, do not show TOC
2945 if( $numMatches < 4 ) {
2946 $doShowToc = false;
2947 }
2948
2949 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2950 # override above conditions and always show TOC at that place
2951
2952 $mw =& MagicWord::get( MAG_TOC );
2953 if($mw->match( $text ) ) {
2954 $doShowToc = true;
2955 $forceTocHere = true;
2956 } else {
2957 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2958 # override above conditions and always show TOC above first header
2959 $mw =& MagicWord::get( MAG_FORCETOC );
2960 if ($mw->matchAndRemove( $text ) ) {
2961 $doShowToc = true;
2962 }
2963 }
2964
2965 # Never ever show TOC if no headers
2966 if( $numMatches < 1 ) {
2967 $doShowToc = false;
2968 }
2969
2970 # We need this to perform operations on the HTML
2971 $sk =& $this->mOptions->getSkin();
2972
2973 # headline counter
2974 $headlineCount = 0;
2975 $sectionCount = 0; # headlineCount excluding template sections
2976
2977 # Ugh .. the TOC should have neat indentation levels which can be
2978 # passed to the skin functions. These are determined here
2979 $toc = '';
2980 $full = '';
2981 $head = array();
2982 $sublevelCount = array();
2983 $levelCount = array();
2984 $toclevel = 0;
2985 $level = 0;
2986 $prevlevel = 0;
2987 $toclevel = 0;
2988 $prevtoclevel = 0;
2989
2990 foreach( $matches[3] as $headline ) {
2991 $istemplate = 0;
2992 $templatetitle = '';
2993 $templatesection = 0;
2994 $numbering = '';
2995
2996 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2997 $istemplate = 1;
2998 $templatetitle = base64_decode($mat[1]);
2999 $templatesection = 1 + (int)base64_decode($mat[2]);
3000 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3001 }
3002
3003 if( $toclevel ) {
3004 $prevlevel = $level;
3005 $prevtoclevel = $toclevel;
3006 }
3007 $level = $matches[1][$headlineCount];
3008
3009 if( $doNumberHeadings || $doShowToc ) {
3010
3011 if ( $level > $prevlevel ) {
3012 # Increase TOC level
3013 $toclevel++;
3014 $sublevelCount[$toclevel] = 0;
3015 $toc .= $sk->tocIndent();
3016 }
3017 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3018 # Decrease TOC level, find level to jump to
3019
3020 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3021 # Can only go down to level 1
3022 $toclevel = 1;
3023 } else {
3024 for ($i = $toclevel; $i > 0; $i--) {
3025 if ( $levelCount[$i] == $level ) {
3026 # Found last matching level
3027 $toclevel = $i;
3028 break;
3029 }
3030 elseif ( $levelCount[$i] < $level ) {
3031 # Found first matching level below current level
3032 $toclevel = $i + 1;
3033 break;
3034 }
3035 }
3036 }
3037
3038 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3039 }
3040 else {
3041 # No change in level, end TOC line
3042 $toc .= $sk->tocLineEnd();
3043 }
3044
3045 $levelCount[$toclevel] = $level;
3046
3047 # count number of headlines for each level
3048 @$sublevelCount[$toclevel]++;
3049 $dot = 0;
3050 for( $i = 1; $i <= $toclevel; $i++ ) {
3051 if( !empty( $sublevelCount[$i] ) ) {
3052 if( $dot ) {
3053 $numbering .= '.';
3054 }
3055 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3056 $dot = 1;
3057 }
3058 }
3059 }
3060
3061 # The canonized header is a version of the header text safe to use for links
3062 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3063 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
3064 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
3065
3066 # Remove link placeholders by the link text.
3067 # <!--LINK number-->
3068 # turns into
3069 # link text with suffix
3070 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3071 "\$this->mLinkHolders['texts'][\$1]",
3072 $canonized_headline );
3073 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3074 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3075 $canonized_headline );
3076
3077 # strip out HTML
3078 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3079 $tocline = trim( $canonized_headline );
3080 # Save headline for section edit hint before it's escaped
3081 $headline_hint = trim( $canonized_headline );
3082 $canonized_headline = Sanitizer::escapeId( $tocline );
3083 $refers[$headlineCount] = $canonized_headline;
3084
3085 # count how many in assoc. array so we can track dupes in anchors
3086 @$refers[$canonized_headline]++;
3087 $refcount[$headlineCount]=$refers[$canonized_headline];
3088
3089 # Don't number the heading if it is the only one (looks silly)
3090 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3091 # the two are different if the line contains a link
3092 $headline=$numbering . ' ' . $headline;
3093 }
3094
3095 # Create the anchor for linking from the TOC to the section
3096 $anchor = $canonized_headline;
3097 if($refcount[$headlineCount] > 1 ) {
3098 $anchor .= '_' . $refcount[$headlineCount];
3099 }
3100 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3101 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3102 }
3103 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3104 if ( empty( $head[$headlineCount] ) ) {
3105 $head[$headlineCount] = '';
3106 }
3107 if( $istemplate )
3108 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3109 else
3110 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1, $headline_hint);
3111 }
3112
3113 # give headline the correct <h#> tag
3114 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3115
3116 $headlineCount++;
3117 if( !$istemplate )
3118 $sectionCount++;
3119 }
3120
3121 if( $doShowToc ) {
3122 $toc .= $sk->tocUnindent( $toclevel - 1 );
3123 $toc = $sk->tocList( $toc );
3124 }
3125
3126 # split up and insert constructed headlines
3127
3128 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3129 $i = 0;
3130
3131 foreach( $blocks as $block ) {
3132 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3133 # This is the [edit] link that appears for the top block of text when
3134 # section editing is enabled
3135
3136 # Disabled because it broke block formatting
3137 # For example, a bullet point in the top line
3138 # $full .= $sk->editSectionLink(0);
3139 }
3140 $full .= $block;
3141 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3142 # Top anchor now in skin
3143 $full = $full.$toc;
3144 }
3145
3146 if( !empty( $head[$i] ) ) {
3147 $full .= $head[$i];
3148 }
3149 $i++;
3150 }
3151 if($forceTocHere) {
3152 $mw =& MagicWord::get( MAG_TOC );
3153 return $mw->replace( $toc, $full );
3154 } else {
3155 return $full;
3156 }
3157 }
3158
3159 /**
3160 * Return an HTML link for the "ISBN 123456" text
3161 * @access private
3162 */
3163 function magicISBN( $text ) {
3164 $fname = 'Parser::magicISBN';
3165 wfProfileIn( $fname );
3166
3167 $a = split( 'ISBN ', ' '.$text );
3168 if ( count ( $a ) < 2 ) {
3169 wfProfileOut( $fname );
3170 return $text;
3171 }
3172 $text = substr( array_shift( $a ), 1);
3173 $valid = '0123456789-Xx';
3174
3175 foreach ( $a as $x ) {
3176 # hack: don't replace inside thumbnail title/alt
3177 # attributes
3178 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3179 $text .= "ISBN $x";
3180 continue;
3181 }
3182
3183 $isbn = $blank = '' ;
3184 while ( ' ' == $x{0} ) {
3185 $blank .= ' ';
3186 $x = substr( $x, 1 );
3187 }
3188 if ( $x == '' ) { # blank isbn
3189 $text .= "ISBN $blank";
3190 continue;
3191 }
3192 while ( strstr( $valid, $x{0} ) != false ) {
3193 $isbn .= $x{0};
3194 $x = substr( $x, 1 );
3195 }
3196 $num = str_replace( '-', '', $isbn );
3197 $num = str_replace( ' ', '', $num );
3198 $num = str_replace( 'x', 'X', $num );
3199
3200 if ( '' == $num ) {
3201 $text .= "ISBN $blank$x";
3202 } else {
3203 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
3204 $text .= '<a href="' .
3205 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3206 "\" class=\"internal\">ISBN $isbn</a>";
3207 $text .= $x;
3208 }
3209 }
3210 wfProfileOut( $fname );
3211 return $text;
3212 }
3213
3214 /**
3215 * Return an HTML link for the "RFC 1234" text
3216 *
3217 * @access private
3218 * @param string $text Text to be processed
3219 * @param string $keyword Magic keyword to use (default RFC)
3220 * @param string $urlmsg Interface message to use (default rfcurl)
3221 * @return string
3222 */
3223 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3224
3225 $valid = '0123456789';
3226 $internal = false;
3227
3228 $a = split( $keyword, ' '.$text );
3229 if ( count ( $a ) < 2 ) {
3230 return $text;
3231 }
3232 $text = substr( array_shift( $a ), 1);
3233
3234 /* Check if keyword is preceed by [[.
3235 * This test is made here cause of the array_shift above
3236 * that prevent the test to be done in the foreach.
3237 */
3238 if ( substr( $text, -2 ) == '[[' ) {
3239 $internal = true;
3240 }
3241
3242 foreach ( $a as $x ) {
3243 /* token might be empty if we have RFC RFC 1234 */
3244 if ( $x=='' ) {
3245 $text.=$keyword;
3246 continue;
3247 }
3248
3249 # hack: don't replace inside thumbnail title/alt
3250 # attributes
3251 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3252 $text .= $keyword . $x;
3253 continue;
3254 }
3255
3256 $id = $blank = '' ;
3257
3258 /** remove and save whitespaces in $blank */
3259 while ( $x{0} == ' ' ) {
3260 $blank .= ' ';
3261 $x = substr( $x, 1 );
3262 }
3263
3264 /** remove and save the rfc number in $id */
3265 while ( strstr( $valid, $x{0} ) != false ) {
3266 $id .= $x{0};
3267 $x = substr( $x, 1 );
3268 }
3269
3270 if ( $id == '' ) {
3271 /* call back stripped spaces*/
3272 $text .= $keyword.$blank.$x;
3273 } elseif( $internal ) {
3274 /* normal link */
3275 $text .= $keyword.$id.$x;
3276 } else {
3277 /* build the external link*/
3278 $url = wfMsg( $urlmsg, $id);
3279 $sk =& $this->mOptions->getSkin();
3280 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3281 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3282 }
3283
3284 /* Check if the next RFC keyword is preceed by [[ */
3285 $internal = ( substr($x,-2) == '[[' );
3286 }
3287 return $text;
3288 }
3289
3290 /**
3291 * Transform wiki markup when saving a page by doing \r\n -> \n
3292 * conversion, substitting signatures, {{subst:}} templates, etc.
3293 *
3294 * @param string $text the text to transform
3295 * @param Title &$title the Title object for the current article
3296 * @param User &$user the User object describing the current user
3297 * @param ParserOptions $options parsing options
3298 * @param bool $clearState whether to clear the parser state first
3299 * @return string the altered wiki markup
3300 * @access public
3301 */
3302 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3303 $this->mOptions = $options;
3304 $this->mTitle =& $title;
3305 $this->mOutputType = OT_WIKI;
3306
3307 if ( $clearState ) {
3308 $this->clearState();
3309 }
3310
3311 $stripState = false;
3312 $pairs = array(
3313 "\r\n" => "\n",
3314 );
3315 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3316 $text = $this->strip( $text, $stripState, true );
3317 $text = $this->pstPass2( $text, $user );
3318 $text = $this->unstrip( $text, $stripState );
3319 $text = $this->unstripNoWiki( $text, $stripState );
3320 return $text;
3321 }
3322
3323 /**
3324 * Pre-save transform helper function
3325 * @access private
3326 */
3327 function pstPass2( $text, &$user ) {
3328 global $wgContLang, $wgLocaltimezone;
3329
3330 /* Note: This is the timestamp saved as hardcoded wikitext to
3331 * the database, we use $wgContLang here in order to give
3332 * everyone the same signiture and use the default one rather
3333 * than the one selected in each users preferences.
3334 */
3335 if ( isset( $wgLocaltimezone ) ) {
3336 $oldtz = getenv( 'TZ' );
3337 putenv( 'TZ='.$wgLocaltimezone );
3338 }
3339 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3340 ' (' . date( 'T' ) . ')';
3341 if ( isset( $wgLocaltimezone ) ) {
3342 putenv( 'TZ='.$oldtz );
3343 }
3344
3345 # Variable replacement
3346 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3347 $text = $this->replaceVariables( $text );
3348
3349 # Signatures
3350 $sigText = $this->getUserSig( $user );
3351 $text = strtr( $text, array(
3352 '~~~~~' => $d,
3353 '~~~~' => "$sigText $d",
3354 '~~~' => $sigText
3355 ) );
3356
3357 # Context links: [[|name]] and [[name (context)|]]
3358 #
3359 global $wgLegalTitleChars;
3360 $tc = "[$wgLegalTitleChars]";
3361 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3362
3363 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3364 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3365
3366 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3367 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3368 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3369 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3370 $context = '';
3371 $t = $this->mTitle->getText();
3372 if ( preg_match( $conpat, $t, $m ) ) {
3373 $context = $m[2];
3374 }
3375 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3376 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3377 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3378
3379 if ( '' == $context ) {
3380 $text = preg_replace( $p2, '[[\\1]]', $text );
3381 } else {
3382 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3383 }
3384
3385 # Trim trailing whitespace
3386 # MAG_END (__END__) tag allows for trailing
3387 # whitespace to be deliberately included
3388 $text = rtrim( $text );
3389 $mw =& MagicWord::get( MAG_END );
3390 $mw->matchAndRemove( $text );
3391
3392 return $text;
3393 }
3394
3395 /**
3396 * Fetch the user's signature text, if any, and normalize to
3397 * validated, ready-to-insert wikitext.
3398 *
3399 * @param User $user
3400 * @return string
3401 * @access private
3402 */
3403 function getUserSig( &$user ) {
3404 $username = $user->getName();
3405 $nickname = $user->getOption( 'nickname' );
3406 $nickname = $nickname === '' ? $username : $nickname;
3407
3408 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3409 # Sig. might contain markup; validate this
3410 if( $this->validateSig( $nickname ) !== false ) {
3411 # Validated; clean up (if needed) and return it
3412 return( $this->cleanSig( $nickname ) );
3413 } else {
3414 # Failed to validate; fall back to the default
3415 $nickname = $username;
3416 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3417 }
3418 }
3419
3420 # If we're still here, make it a link to the user page
3421 $userpage = $user->getUserPage();
3422 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3423 }
3424
3425 /**
3426 * Check that the user's signature contains no bad XML
3427 *
3428 * @param string $text
3429 * @return mixed An expanded string, or false if invalid.
3430 */
3431 function validateSig( $text ) {
3432 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3433 }
3434
3435 /**
3436 * Clean up signature text
3437 *
3438 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3439 * 2) Substitute all transclusions
3440 *
3441 * @param string $text
3442 * @return string Signature text
3443 */
3444 function cleanSig( $text ) {
3445 $substWord = MagicWord::get( MAG_SUBST );
3446 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3447 $substText = '{{' . $substWord->getSynonym( 0 );
3448
3449 $text = preg_replace( $substRegex, $substText, $text );
3450 $text = preg_replace( '/~{3,5}/', '', $text );
3451 $text = $this->replaceVariables( $text );
3452
3453 return $text;
3454 }
3455
3456 /**
3457 * Set up some variables which are usually set up in parse()
3458 * so that an external function can call some class members with confidence
3459 * @access public
3460 */
3461 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3462 $this->mTitle =& $title;
3463 $this->mOptions = $options;
3464 $this->mOutputType = $outputType;
3465 if ( $clearState ) {
3466 $this->clearState();
3467 }
3468 }
3469
3470 /**
3471 * Transform a MediaWiki message by replacing magic variables.
3472 *
3473 * @param string $text the text to transform
3474 * @param ParserOptions $options options
3475 * @return string the text with variables substituted
3476 * @access public
3477 */
3478 function transformMsg( $text, $options ) {
3479 global $wgTitle;
3480 static $executing = false;
3481
3482 $fname = "Parser::transformMsg";
3483
3484 # Guard against infinite recursion
3485 if ( $executing ) {
3486 return $text;
3487 }
3488 $executing = true;
3489
3490 wfProfileIn($fname);
3491
3492 $this->mTitle = $wgTitle;
3493 $this->mOptions = $options;
3494 $this->mOutputType = OT_MSG;
3495 $this->clearState();
3496 $text = $this->replaceVariables( $text );
3497
3498 $executing = false;
3499 wfProfileOut($fname);
3500 return $text;
3501 }
3502
3503 /**
3504 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3505 * The callback should have the following form:
3506 * function myParserHook( $text, $params, &$parser ) { ... }
3507 *
3508 * Transform and return $text. Use $parser for any required context, e.g. use
3509 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3510 *
3511 * @access public
3512 *
3513 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3514 * @param mixed $callback The callback function (and object) to use for the tag
3515 *
3516 * @return The old value of the mTagHooks array associated with the hook
3517 */
3518 function setHook( $tag, $callback ) {
3519 $oldVal = @$this->mTagHooks[$tag];
3520 $this->mTagHooks[$tag] = $callback;
3521
3522 return $oldVal;
3523 }
3524
3525 /**
3526 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3527 * Placeholders created in Skin::makeLinkObj()
3528 * Returns an array of links found, indexed by PDBK:
3529 * 0 - broken
3530 * 1 - normal link
3531 * 2 - stub
3532 * $options is a bit field, RLH_FOR_UPDATE to select for update
3533 */
3534 function replaceLinkHolders( &$text, $options = 0 ) {
3535 global $wgUser;
3536 global $wgOutputReplace;
3537
3538 $fname = 'Parser::replaceLinkHolders';
3539 wfProfileIn( $fname );
3540
3541 $pdbks = array();
3542 $colours = array();
3543 $sk =& $this->mOptions->getSkin();
3544 $linkCache =& LinkCache::singleton();
3545
3546 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3547 wfProfileIn( $fname.'-check' );
3548 $dbr =& wfGetDB( DB_SLAVE );
3549 $page = $dbr->tableName( 'page' );
3550 $threshold = $wgUser->getOption('stubthreshold');
3551
3552 # Sort by namespace
3553 asort( $this->mLinkHolders['namespaces'] );
3554
3555 # Generate query
3556 $query = false;
3557 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3558 # Make title object
3559 $title = $this->mLinkHolders['titles'][$key];
3560
3561 # Skip invalid entries.
3562 # Result will be ugly, but prevents crash.
3563 if ( is_null( $title ) ) {
3564 continue;
3565 }
3566 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3567
3568 # Check if it's a static known link, e.g. interwiki
3569 if ( $title->isAlwaysKnown() ) {
3570 $colours[$pdbk] = 1;
3571 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3572 $colours[$pdbk] = 1;
3573 $this->mOutput->addLink( $title, $id );
3574 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3575 $colours[$pdbk] = 0;
3576 } else {
3577 # Not in the link cache, add it to the query
3578 if ( !isset( $current ) ) {
3579 $current = $ns;
3580 $query = "SELECT page_id, page_namespace, page_title";
3581 if ( $threshold > 0 ) {
3582 $query .= ', page_len, page_is_redirect';
3583 }
3584 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3585 } elseif ( $current != $ns ) {
3586 $current = $ns;
3587 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3588 } else {
3589 $query .= ', ';
3590 }
3591
3592 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3593 }
3594 }
3595 if ( $query ) {
3596 $query .= '))';
3597 if ( $options & RLH_FOR_UPDATE ) {
3598 $query .= ' FOR UPDATE';
3599 }
3600
3601 $res = $dbr->query( $query, $fname );
3602
3603 # Fetch data and form into an associative array
3604 # non-existent = broken
3605 # 1 = known
3606 # 2 = stub
3607 while ( $s = $dbr->fetchObject($res) ) {
3608 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3609 $pdbk = $title->getPrefixedDBkey();
3610 $linkCache->addGoodLinkObj( $s->page_id, $title );
3611 $this->mOutput->addLink( $title, $s->page_id );
3612
3613 if ( $threshold > 0 ) {
3614 $size = $s->page_len;
3615 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3616 $colours[$pdbk] = 1;
3617 } else {
3618 $colours[$pdbk] = 2;
3619 }
3620 } else {
3621 $colours[$pdbk] = 1;
3622 }
3623 }
3624 }
3625 wfProfileOut( $fname.'-check' );
3626
3627 # Construct search and replace arrays
3628 wfProfileIn( $fname.'-construct' );
3629 $wgOutputReplace = array();
3630 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3631 $pdbk = $pdbks[$key];
3632 $searchkey = "<!--LINK $key-->";
3633 $title = $this->mLinkHolders['titles'][$key];
3634 if ( empty( $colours[$pdbk] ) ) {
3635 $linkCache->addBadLinkObj( $title );
3636 $colours[$pdbk] = 0;
3637 $this->mOutput->addLink( $title, 0 );
3638 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3639 $this->mLinkHolders['texts'][$key],
3640 $this->mLinkHolders['queries'][$key] );
3641 } elseif ( $colours[$pdbk] == 1 ) {
3642 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3643 $this->mLinkHolders['texts'][$key],
3644 $this->mLinkHolders['queries'][$key] );
3645 } elseif ( $colours[$pdbk] == 2 ) {
3646 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3647 $this->mLinkHolders['texts'][$key],
3648 $this->mLinkHolders['queries'][$key] );
3649 }
3650 }
3651 wfProfileOut( $fname.'-construct' );
3652
3653 # Do the thing
3654 wfProfileIn( $fname.'-replace' );
3655
3656 $text = preg_replace_callback(
3657 '/(<!--LINK .*?-->)/',
3658 "wfOutputReplaceMatches",
3659 $text);
3660
3661 wfProfileOut( $fname.'-replace' );
3662 }
3663
3664 # Now process interwiki link holders
3665 # This is quite a bit simpler than internal links
3666 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
3667 wfProfileIn( $fname.'-interwiki' );
3668 # Make interwiki link HTML
3669 $wgOutputReplace = array();
3670 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
3671 $title = $this->mInterwikiLinkHolders['titles'][$key];
3672 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3673 }
3674
3675 $text = preg_replace_callback(
3676 '/<!--IWLINK (.*?)-->/',
3677 "wfOutputReplaceMatches",
3678 $text );
3679 wfProfileOut( $fname.'-interwiki' );
3680 }
3681
3682 wfProfileOut( $fname );
3683 return $colours;
3684 }
3685
3686 /**
3687 * Replace <!--LINK--> link placeholders with plain text of links
3688 * (not HTML-formatted).
3689 * @param string $text
3690 * @return string
3691 */
3692 function replaceLinkHoldersText( $text ) {
3693 $fname = 'Parser::replaceLinkHoldersText';
3694 wfProfileIn( $fname );
3695
3696 $text = preg_replace_callback(
3697 '/<!--(LINK|IWLINK) (.*?)-->/',
3698 array( &$this, 'replaceLinkHoldersTextCallback' ),
3699 $text );
3700
3701 wfProfileOut( $fname );
3702 return $text;
3703 }
3704
3705 /**
3706 * @param array $matches
3707 * @return string
3708 * @access private
3709 */
3710 function replaceLinkHoldersTextCallback( $matches ) {
3711 $type = $matches[1];
3712 $key = $matches[2];
3713 if( $type == 'LINK' ) {
3714 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
3715 return $this->mLinkHolders['texts'][$key];
3716 }
3717 } elseif( $type == 'IWLINK' ) {
3718 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
3719 return $this->mInterwikiLinkHolders['texts'][$key];
3720 }
3721 }
3722 return $matches[0];
3723 }
3724
3725 /**
3726 * Renders an image gallery from a text with one line per image.
3727 * text labels may be given by using |-style alternative text. E.g.
3728 * Image:one.jpg|The number "1"
3729 * Image:tree.jpg|A tree
3730 * given as text will return the HTML of a gallery with two images,
3731 * labeled 'The number "1"' and
3732 * 'A tree'.
3733 */
3734 function renderImageGallery( $text ) {
3735 # Setup the parser
3736 $parserOptions = new ParserOptions;
3737 $localParser = new Parser();
3738
3739 $ig = new ImageGallery();
3740 $ig->setShowBytes( false );
3741 $ig->setShowFilename( false );
3742 $lines = explode( "\n", $text );
3743
3744 foreach ( $lines as $line ) {
3745 # match lines like these:
3746 # Image:someimage.jpg|This is some image
3747 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3748 # Skip empty lines
3749 if ( count( $matches ) == 0 ) {
3750 continue;
3751 }
3752 $nt =& Title::newFromText( $matches[1] );
3753 if( is_null( $nt ) ) {
3754 # Bogus title. Ignore these so we don't bomb out later.
3755 continue;
3756 }
3757 if ( isset( $matches[3] ) ) {
3758 $label = $matches[3];
3759 } else {
3760 $label = '';
3761 }
3762
3763 $pout = $localParser->parse( $label , $this->mTitle, $parserOptions );
3764 $html = $pout->getText();
3765
3766 $ig->add( new Image( $nt ), $html );
3767 $this->mOutput->addImage( $nt->getDBkey() );
3768 }
3769 return $ig->toHTML();
3770 }
3771
3772 /**
3773 * Parse image options text and use it to make an image
3774 */
3775 function makeImage( &$nt, $options ) {
3776 global $wgUseImageResize;
3777
3778 $align = '';
3779
3780 # Check if the options text is of the form "options|alt text"
3781 # Options are:
3782 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3783 # * left no resizing, just left align. label is used for alt= only
3784 # * right same, but right aligned
3785 # * none same, but not aligned
3786 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3787 # * center center the image
3788 # * framed Keep original image size, no magnify-button.
3789
3790 $part = explode( '|', $options);
3791
3792 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
3793 $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
3794 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
3795 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
3796 $mwNone =& MagicWord::get( MAG_IMG_NONE );
3797 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
3798 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
3799 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
3800 $caption = '';
3801
3802 $width = $height = $framed = $thumb = false;
3803 $manual_thumb = '' ;
3804
3805 foreach( $part as $key => $val ) {
3806 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3807 $thumb=true;
3808 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3809 # use manually specified thumbnail
3810 $thumb=true;
3811 $manual_thumb = $match;
3812 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3813 # remember to set an alignment, don't render immediately
3814 $align = 'right';
3815 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3816 # remember to set an alignment, don't render immediately
3817 $align = 'left';
3818 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3819 # remember to set an alignment, don't render immediately
3820 $align = 'center';
3821 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3822 # remember to set an alignment, don't render immediately
3823 $align = 'none';
3824 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3825 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3826 # $match is the image width in pixels
3827 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3828 $width = intval( $m[1] );
3829 $height = intval( $m[2] );
3830 } else {
3831 $width = intval($match);
3832 }
3833 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3834 $framed=true;
3835 } else {
3836 $caption = $val;
3837 }
3838 }
3839 # Strip bad stuff out of the alt text
3840 $alt = $this->replaceLinkHoldersText( $caption );
3841
3842 # make sure there are no placeholders in thumbnail attributes
3843 # that are later expanded to html- so expand them now and
3844 # remove the tags
3845 $alt = $this->unstrip($alt, $this->mStripState);
3846 $alt = Sanitizer::stripAllTags( $alt );
3847
3848 # Linker does the rest
3849 $sk =& $this->mOptions->getSkin();
3850 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3851 }
3852
3853 /**
3854 * Set a flag in the output object indicating that the content is dynamic and
3855 * shouldn't be cached.
3856 */
3857 function disableCache() {
3858 $this->mOutput->mCacheTime = -1;
3859 }
3860
3861 /**#@+
3862 * Callback from the Sanitizer for expanding items found in HTML attribute
3863 * values, so they can be safely tested and escaped.
3864 * @param string $text
3865 * @param array $args
3866 * @return string
3867 * @access private
3868 */
3869 function attributeStripCallback( &$text, $args ) {
3870 $text = $this->replaceVariables( $text, $args );
3871 $text = $this->unstripForHTML( $text );
3872 return $text;
3873 }
3874
3875 function unstripForHTML( $text ) {
3876 $text = $this->unstrip( $text, $this->mStripState );
3877 $text = $this->unstripNoWiki( $text, $this->mStripState );
3878 return $text;
3879 }
3880 /**#@-*/
3881
3882 /**#@+
3883 * Accessor/mutator
3884 */
3885 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
3886 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
3887 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
3888 /**#@-*/
3889
3890 /**#@+
3891 * Accessor
3892 */
3893 function getTags() { return array_keys( $this->mTagHooks ); }
3894 /**#@-*/
3895 }
3896
3897 /**
3898 * @todo document
3899 * @package MediaWiki
3900 */
3901 class ParserOutput
3902 {
3903 var $mText, # The output text
3904 $mLanguageLinks, # List of the full text of language links, in the order they appear
3905 $mCategories, # Map of category names to sort keys
3906 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3907 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
3908 $mVersion, # Compatibility check
3909 $mTitleText, # title text of the chosen language variant
3910 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3911 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3912 $mImages, # DB keys of the images used, in the array key only
3913 $mExternalLinks; # External link URLs, in the key only
3914
3915 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3916 $containsOldMagic = false, $titletext = '' )
3917 {
3918 $this->mText = $text;
3919 $this->mLanguageLinks = $languageLinks;
3920 $this->mCategories = $categoryLinks;
3921 $this->mContainsOldMagic = $containsOldMagic;
3922 $this->mCacheTime = '';
3923 $this->mVersion = MW_PARSER_VERSION;
3924 $this->mTitleText = $titletext;
3925 $this->mLinks = array();
3926 $this->mTemplates = array();
3927 $this->mImages = array();
3928 $this->mExternalLinks = array();
3929 }
3930
3931 function getText() { return $this->mText; }
3932 function getLanguageLinks() { return $this->mLanguageLinks; }
3933 function getCategoryLinks() { return array_keys( $this->mCategories ); }
3934 function &getCategories() { return $this->mCategories; }
3935 function getCacheTime() { return $this->mCacheTime; }
3936 function getTitleText() { return $this->mTitleText; }
3937 function &getLinks() { return $this->mLinks; }
3938 function &getTemplates() { return $this->mTemplates; }
3939 function &getImages() { return $this->mImages; }
3940 function &getExternalLinks() { return $this->mExternalLinks; }
3941
3942 function containsOldMagic() { return $this->mContainsOldMagic; }
3943 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3944 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3945 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
3946 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3947 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3948 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
3949
3950 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
3951 function addImage( $name ) { $this->mImages[$name] = 1; }
3952 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
3953 function addExternalLink( $url ) { $this->mExternalLinks[$url] = 1; }
3954
3955 function addLink( $title, $id ) {
3956 $ns = $title->getNamespace();
3957 $dbk = $title->getDBkey();
3958 if ( !isset( $this->mLinks[$ns] ) ) {
3959 $this->mLinks[$ns] = array();
3960 }
3961 $this->mLinks[$ns][$dbk] = $id;
3962 }
3963
3964 function addTemplate( $title, $id ) {
3965 $ns = $title->getNamespace();
3966 $dbk = $title->getDBkey();
3967 if ( !isset( $this->mTemplates[$ns] ) ) {
3968 $this->mTemplates[$ns] = array();
3969 }
3970 $this->mTemplates[$ns][$dbk] = $id;
3971 }
3972
3973 /**
3974 * @deprecated
3975 */
3976 /*
3977 function merge( $other ) {
3978 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3979 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3980 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3981 }*/
3982
3983 /**
3984 * Return true if this cached output object predates the global or
3985 * per-article cache invalidation timestamps, or if it comes from
3986 * an incompatible older version.
3987 *
3988 * @param string $touched the affected article's last touched timestamp
3989 * @return bool
3990 * @access public
3991 */
3992 function expired( $touched ) {
3993 global $wgCacheEpoch;
3994 return $this->getCacheTime() == -1 || // parser says it's uncacheable
3995 $this->getCacheTime() < $touched ||
3996 $this->getCacheTime() <= $wgCacheEpoch ||
3997 !isset( $this->mVersion ) ||
3998 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3999 }
4000 }
4001
4002 /**
4003 * Set options of the Parser
4004 * @todo document
4005 * @package MediaWiki
4006 */
4007 class ParserOptions
4008 {
4009 # All variables are private
4010 var $mUseTeX; # Use texvc to expand <math> tags
4011 var $mUseDynamicDates; # Use DateFormatter to format dates
4012 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4013 var $mAllowExternalImages; # Allow external images inline
4014 var $mAllowExternalImagesFrom; # If not, any exception?
4015 var $mSkin; # Reference to the preferred skin
4016 var $mDateFormat; # Date format index
4017 var $mEditSection; # Create "edit section" links
4018 var $mNumberHeadings; # Automatically number headings
4019 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4020 var $mTidy; # Ask for tidy cleanup
4021
4022 function getUseTeX() { return $this->mUseTeX; }
4023 function getUseDynamicDates() { return $this->mUseDynamicDates; }
4024 function getInterwikiMagic() { return $this->mInterwikiMagic; }
4025 function getAllowExternalImages() { return $this->mAllowExternalImages; }
4026 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
4027 function &getSkin() { return $this->mSkin; }
4028 function getDateFormat() { return $this->mDateFormat; }
4029 function getEditSection() { return $this->mEditSection; }
4030 function getNumberHeadings() { return $this->mNumberHeadings; }
4031 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
4032 function getTidy() { return $this->mTidy; }
4033
4034 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
4035 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
4036 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
4037 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
4038 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
4039 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
4040 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
4041 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
4042 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
4043 function setTidy( $x ) { return wfSetVar( $this->mTidy, $x); }
4044 function setSkin( &$x ) { $this->mSkin =& $x; }
4045
4046 function ParserOptions() {
4047 global $wgUser;
4048 $this->initialiseFromUser( $wgUser );
4049 }
4050
4051 /**
4052 * Get parser options
4053 * @static
4054 */
4055 function newFromUser( &$user ) {
4056 $popts = new ParserOptions;
4057 $popts->initialiseFromUser( $user );
4058 return $popts;
4059 }
4060
4061 /** Get user options */
4062 function initialiseFromUser( &$userInput ) {
4063 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4064 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4065 $fname = 'ParserOptions::initialiseFromUser';
4066 wfProfileIn( $fname );
4067 if ( !$userInput ) {
4068 $user = new User;
4069 $user->setLoaded( true );
4070 } else {
4071 $user =& $userInput;
4072 }
4073
4074 $this->mUseTeX = $wgUseTeX;
4075 $this->mUseDynamicDates = $wgUseDynamicDates;
4076 $this->mInterwikiMagic = $wgInterwikiMagic;
4077 $this->mAllowExternalImages = $wgAllowExternalImages;
4078 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
4079 wfProfileIn( $fname.'-skin' );
4080 $this->mSkin =& $user->getSkin();
4081 wfProfileOut( $fname.'-skin' );
4082 $this->mDateFormat = $user->getOption( 'date' );
4083 $this->mEditSection = true;
4084 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
4085 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
4086 $this->mTidy = false;
4087 wfProfileOut( $fname );
4088 }
4089 }
4090
4091 /**
4092 * Callback function used by Parser::replaceLinkHolders()
4093 * to substitute link placeholders.
4094 */
4095 function &wfOutputReplaceMatches( $matches ) {
4096 global $wgOutputReplace;
4097 return $wgOutputReplace[$matches[1]];
4098 }
4099
4100 /**
4101 * Return the total number of articles
4102 */
4103 function wfNumberOfArticles() {
4104 global $wgNumberOfArticles;
4105
4106 wfLoadSiteStats();
4107 return $wgNumberOfArticles;
4108 }
4109
4110 /**
4111 * Return the number of files
4112 */
4113 function wfNumberOfFiles() {
4114 $fname = 'Parser::wfNumberOfFiles';
4115
4116 wfProfileIn( $fname );
4117 $dbr =& wfGetDB( DB_SLAVE );
4118 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
4119 wfProfileOut( $fname );
4120
4121 return $res;
4122 }
4123
4124 /**
4125 * Get various statistics from the database
4126 * @access private
4127 */
4128 function wfLoadSiteStats() {
4129 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4130 $fname = 'wfLoadSiteStats';
4131
4132 if ( -1 != $wgNumberOfArticles ) return;
4133 $dbr =& wfGetDB( DB_SLAVE );
4134 $s = $dbr->selectRow( 'site_stats',
4135 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4136 array( 'ss_row_id' => 1 ), $fname
4137 );
4138
4139 if ( $s === false ) {
4140 return;
4141 } else {
4142 $wgTotalViews = $s->ss_total_views;
4143 $wgTotalEdits = $s->ss_total_edits;
4144 $wgNumberOfArticles = $s->ss_good_articles;
4145 }
4146 }
4147
4148 /**
4149 * Escape html tags
4150 * Basically replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
4151 *
4152 * @param string $in Text that might contain HTML tags
4153 * @return string Escaped string
4154 */
4155 function wfEscapeHTMLTagsOnly( $in ) {
4156 return str_replace(
4157 array( '"', '>', '<' ),
4158 array( '&quot;', '&gt;', '&lt;' ),
4159 $in );
4160 }
4161
4162 ?>